[英]Method that executes a continuation of a Task in the main thread
我必须创建一个类似于ContinueWith()
,但是将在主Task之后在主线程中执行延续。
我怎样才能做到这一点? 我可以在方法中无休止地检查Task
的状态,并在完成时开始继续执行,但是我认为它不能以这种方式工作:
Task<DayOfWeek> taskA = new Task<DayOfWeek>(() => DateTime.Today.DayOfWeek);
Task<string> continuation = taskA.OurMethod((antecedent) =>
{
return String.Format("Today is {0}.", antecedent.Result);
});
// Because we endlessly checking state of main Task
// Code below will never execute
taskA.Start();
那我可以在这里做什么?
尝试传递“主”线程的Dispatcher
。 例:
Task.Factory.StartNew(()=>
{
// blah
}
.ContinueWith(task=>
{
Application.Current.Dispatcher.BeginInvoke(new Action(()=>
{
// yay, on the UI thread...
}
}
假设“主”线程是UI线程。 如果不是,那么请在创建线程之后获取该线程的调度程序。 使用该调度Application.Current
代替Application.Current
的调度Application.Current
(即CurrentDispatcher
)。
您可以为这样的过程创建ExtensionMethod
。 这是一个示例实现
static class ExtensionMethods
{
public static Task ContinueOnUI(this Task task, Action continuation)
{
return task.ContinueWith((arg) =>
{
Dispatcher.CurrentDispatcher.Invoke(continuation);
});
}
}
像这样食用。
Task run = new Task(() =>
{
Debug.WriteLine("Testing");
});
run.ContinueOnUI(() =>
{
Notify += "\nExecuted On UI"; // Notify is bound on a UI control
});
run.Start();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.