开发者

What is the best/safest way to access the main UI thread?

I would like to know, what is the best/safest way to access the main UI thread from another thread.

Should i use Dispatcher.BeginInvoke?

_cancelationTokenSource = new CancellationTokenSource();
        new Task(() =>
            {
                Dispatcher.BeginInvoke((Action)(() =>
                {
                    //process data
                }));
            }, _cancelationTokenSource.Token, TaskCreationOptions.LongRunning).Start();

or should i use Dispatcher.Invoke?

    _cancelationTokenSource = new CancellationTokenSource();
        new Task(() =>
            {
                Dispatcher.Invoke((Action)(() =>
                {
                    //process data
                }));
            }, _cancelationTokenSource.Token, TaskCreationOptions.LongRunning).Start();

What is the main difference between the 2 Invoke methods?开发者_高级运维

What will the performance impact be when using BeginInvoke and Invoke?

Most important, i would like to keep my UI responsive.


Invoke() if you want to call it synchronous and BeginInvoke() for async .. if you use BeginInvoke you will need to pass the delegate to be called when the operation is finished.

You are already on a background thread so UI will remain responsive either way. Just depends on whether you want this thread's execution to wait for the operation to finish or if you want it done in the background while this thread's execution continues.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜