[英]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.