我需要启用我的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);