我需要編寫擴展方法,它將像Task.ContinueWith()
一樣工作,但在主線程上,並且在Task.ContinueWith()
之後結束。如何編寫當前線程任務繼續,將在標準連續運行後執行?
public static Task ContinueWithOnMainThread(this Task task, Action action) {
return task.ContinueWith(t => action(), TaskScheduler.FromCurrentSynchronizationContext());
}
這種方法可行,但其執行前Task.ContinueWith()
這就是我測試了它:
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
Loaded += delegate {
LogThread("\nInMain ThredId: " + Thread.CurrentThread.ManagedThreadId);
var task = new Task(InTask);
task.ContinueWith(TaskContinue);
task.ContinueWithOnMainThread(ReturnedToMainThread);
task.Start();
};
}
void InTask() {
this.Dispatcher.Invoke(DispatcherPriority.DataBind, (Action<string>)LogThread, "\nInTask ThredId: " + Thread.CurrentThread.ManagedThreadId);
}
void TaskContinue(Task task) {
this.Dispatcher.Invoke(DispatcherPriority.DataBind, (Action<string>)LogThread, "\nTaskContinue ThredId: " + Thread.CurrentThread.ManagedThreadId);
}
void ReturnedToMainThread() {
LogThread("\nReturnedToMainThread ThredId: " + Thread.CurrentThread.ManagedThreadId);
}
void LogThread(string text) {
TB.Text += text;
}
}
您是否試過_anything_?請閱讀[常見問題]和[問] – 2013-04-30 13:46:59
你的情況*真的很不明確 - 你沒有告訴我們你是如何使用它的,或者你是如何診斷問題的。 – 2013-04-30 13:51:08
現在我的情況很明顯嗎? – 2013-04-30 14:03:39