Vijay Rana
Vijay Rana

Reputation: 11

c# new Thread(() to Application.Current.Dispatcher taking long time

I created the new thread inside main thread

     new Thread(() =>
                    {
                       // my code
                       System.Diagnostics.Debug.WriteLine("my code completed");
                       Application.Current.Dispatcher.Invoke(MyMethod, DispatcherPriority.ContextIdle);
                    }).Start();

After executing the my code it take 5-8 seconds to call the MyMethod

I saw in the output window that, given bellow line occurs few times before calling the MyMethod

The thread 0x2954 has exited with code 259 (0x103)

To fix this, I tired to Abort the current thread using Thread.CurrentThread.Abort(); but its not solving my problem. I want to call MyMethod immediately after my code completed.

Upvotes: 0

Views: 387

Answers (1)

Neil
Neil

Reputation: 11889

When you create a thread, a lot of processing takes place before your code actually runs. If you need your code to be more responsive, take a look at thread pools (Task are basically the same thing).

Bear in mind that even with a thread pool it can take a little while to start things off, but it should be much less than starting with a brand new thread.

With your code, what you are doing is starting a thread (which might take a long time), then asking your thread to pass control back to the UI thread, which itself might be busy doing other things and not able to run your code until it is free.

Upvotes: 1

Related Questions