本文介绍了UI 线程上的任务延续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种标准"的方式来指定任务延续应该在创建初始任务的线程上运行?
Is there a 'standard' way to specify that a task continuation should run on the thread from which the initial task was created?
目前我有下面的代码 - 它正在工作,但跟踪调度程序并创建第二个操作似乎是不必要的开销.
Currently I have the code below - it is working but keeping track of the dispatcher and creating a second Action seems like unnecessary overhead.
dispatcher = Dispatcher.CurrentDispatcher;
Task task = Task.Factory.StartNew(() =>
{
DoLongRunningWork();
});
Task UITask= task.ContinueWith(() =>
{
dispatcher.Invoke(new Action(() =>
{
this.TextBlock1.Text = "Complete";
}
});
推荐答案
用TaskScheduler.FromCurrentSynchronizationContext()
调用continuation:
Call the continuation with TaskScheduler.FromCurrentSynchronizationContext()
:
Task UITask= task.ContinueWith(() =>
{
this.TextBlock1.Text = "Complete";
}, TaskScheduler.FromCurrentSynchronizationContext());
这仅适用于当前执行上下文在 UI 线程上的情况.
This is suitable only if the current execution context is on the UI thread.
这篇关于UI 线程上的任务延续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!