我正在使用 WinForms 中的任务从我的 UI 线程中删除昂贵的方法。在我的 updateComplete 和 updateFailed 任务中,我必须将 _updateMessageTaskInProgress 设置为 false 并启用我的控件。有什么方法可以在单独的任务中执行此操作,一旦完成,updateComplete 或 updateFailed 也会继续(因为我目前有重复的代码)?另外,是否有更好的方法来实现 _updateMessageTaskInProgress - 我不希望同时运行多个任务。
private void PerformUpdate()
{
if (!_updateMessageTaskInProgress)
{
LoadButton.Enabled = false;
MonthEndDateEdit.Enabled = false;
BankIssuerListEdit.Enabled = false;
Task updateMessages = Task.Factory.StartNew(() =>
{
_updateMessageTaskInProgress = true;
ExpensiveMethod();
});
// Task runs when updateMessages completes without exception. Runs on UI thread.
Task updateComplete = updateMessages.ContinueWith(update =>
{
DoSuccessfulStuff();
_updateMessageTaskInProgress = false;
LoadButton.Enabled = true;
MonthEndDateEdit.Enabled = true;
BankIssuerListEdit.Enabled = true;
}, System.Threading.CancellationToken.None, TaskContinuationOptions.NotOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
// Task runs when updateMessages completes with exception. Runs on UI thread.
Task updateFailed = updateMessages.ContinueWith(task =>
{
DoFailureStuff();
_updateMessageTaskInProgress = false;
LoadButton.Enabled = true;
MonthEndDateEdit.Enabled = true;
BankIssuerListEdit.Enabled = true;
}, System.Threading.CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
}
}