开发者

WPF Threading question better option

Here are the 2 ways we are using trying to use thread/dispatcher for multi tasking a few things: I am wondering if anyone has any 开发者_JAVA技巧suggestions which one is better option.

Snippet 1:

Thread t = new Thread(new ThreadStart(delegate
                {
                   MyMethod();
                }));
t.IsBackground = true;
t.Start();
t.Join();

Snippet 2:

Dispatcher.CurrentDispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
           (dummyDelegate)delegate
           {
               MyMethod();

           }
    );

Please advise. Thanks N


Neither is "better": they are different.

The first example runs MyMethod on a background thread. So if MyMethod blocks, for example on network activity or doing something computation intensive, this doesn't block the UI thread, and the UI remains responsive. (Though since your sample code blocks and waits, you are currently losing this advantage anyway.) The downside is that MyMethod has to jump through some minor hoops if it wants to read or update the UI.

The second example runs MyMethod on the UI thread. This allows MyMethod to interact without restriction with elements in the UI, but is unsuitable if MyMethod takes a long time because it freezes the UI while MyMethod is running.

So it depends on what MyMethod does. If MyMethod updates a couple of UI elements and then exits, use the second option. If MyMethod loads files or downloads data, and/or performs lengthy computation, use the first.


There is also a third option: use the Threadpool to execute a short-lived asynchronous call. For example:

System.Threading.Threadpool.QueueUserWorkItem(
    delegate(object context)
    {
        // context is unused
        MyMethod();
    });

This will use a thread from the threadpool to execute MyMethod. When the method completes, the thread will be returned to the pool. The advantage of this method is that you don't have to manage the lifetime of the threads yourself, and you don't incure the memory and performance overhead of creating and destroying the thread.


Anything wrong with using good ole BackgroundWorker?

It's not WinForms specific so you can still use it in WPF.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜