0

I am creating a thread using

public static void Invoke(ThreadStart method)
{
    Thread th = default(Thread);
    try 
    {
        th = new Thread(method);
        th.Start();
    } 
    catch (Exception ex) 
    { }
}

and I am calling it as

Invoke(new Threading.ThreadStart(method_name));

In WPF, I need that what this thread does should not hang UI (i.e. an ASync thread should start). What should I do?

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208

3 Answers3

2

If you are using .net 4.5 you can do

    Task.Run( () => 
{
    // your code here
});

In .net 4.0 you can do:

Task.Factory.StartNew(() => 
{
    // your code here
}, 
CancellationToken.None, 
TaskCreationOptions.DenyChildAttach, 
TaskScheduler.Default);
NeddySpaghetti
  • 13,187
  • 5
  • 32
  • 61
1

If you are only using the Thread fore responsive UI look at the System.ComponentModel.BackgroundWorker

this is typiccaly used for responsive UI

If you use the latest version of the framwork, you could also look at the async keyword

Async/await vs BackgroundWorker

Community
  • 1
  • 1
lordkain
  • 3,061
  • 1
  • 13
  • 18
0

If you are using WPF, you can Use BeginInvoke. What is exactly wrong with your Code? This works fine:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace AsyncTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // First Counter (Thread)
            Invoke(new ThreadStart(Do));
            Thread.Sleep(10000);

            // Second Counter (Thread)
            Invoke(new ThreadStart(Do));
            Console.ReadLine();
        }

        public static void Do()
        {
            for (int i = 0; i < 10000000; i++)
            {
                Console.WriteLine("Test: " + i.ToString());
                Thread.Sleep(100);
            }
        }

        public static void Invoke(ThreadStart ThreadStart)
        {
            Thread cCurrentThread = null;
            try
            {
                cCurrentThread = new Thread(ThreadStart);
                cCurrentThread.Start();
            }
            catch (Exception ex)
            {
            }
        }
    }
}
BendEg
  • 20,098
  • 17
  • 57
  • 131