我需要编写扩展方法,它可以像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;
}
}