在主线程中执行任务延续的方法
本文关键字:延续 方法 执行任务 线程 | 更新日期: 2023-09-27 18:33:14
我必须创建一个类似于ContinueWith()
的方法,但将在主任务之后在主线程中执行延续。
我该怎么做?我可以无休止地检查我的方法中的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
的(即 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();