GUIのキャンセルまたは停止ボタンを押すことができるようにする必要があります。しかし、イベントを実行すると GUI がロックされます。そして、私はその理由を理解できますか?
だから私は新しいスレッドを開始し、ループを実行し、キャンセルを押したかどうかを確認します。ループ内で、ジョブを処理するために新しいスレッドを開始し、その後、GUI を更新します。
//this is button click event.
filesToImport = [list of obj, with information abount som task that needs to be done]
TaskScheduler taskScheduler = TaskScheduler.FromCurrentSynchronizationContext(); // current gui context
// start a new thread
Task.Factory.StartNew(() => {
foreach (fics_ds_import job in filesToImport)
{
// have the user cancel();
if (this.CancellationTokenSource.IsCancellationRequested)
{
//this.CancellationTokenSource.Token.ThrowIfCancellationRequested();
break;
}
// start new thread for doing the task, and update the gui.
Task.Factory.StartNew(() => this.DoSomeWork(this.ConnectionStringTxt.Text, job), this.CancellationTokenSource.Token, TaskCreationOptions.None, taskScheduler).ContinueWith(o => this.UpdateProcessStatus(), taskScheduler);
}
}, this.CancellationTokenSource.Token, TaskCreationOptions.LongRunning, taskScheduler);