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?

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

.NET 4.0 doesn't have DenyChildAttach. Otherwise, this is a good answer.
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

Comments

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)
            {
            }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.