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;
}
}