我在WinForms中使用任務從我的UI線程中刪除昂貴的方法。在我的updateComplete和updateFailed任務中,我必須將_updateMessageTaskInProgress設置爲false並啓用我的控件。有沒有什麼辦法可以在一個單獨的任務中完成這個任務,一旦完成任務,updateComplete或updateFailed就會繼續執行(因爲我目前有重複的代碼)?另外,有沒有更好的實現_updateMessageTaskInProgress的方法 - 我不想同時運行多個任務。任務延續以保持UI線程響應
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());
}
}
你的'_updateMessageTaskInProgress'有一個競爭條件:如果兩個任務同時啓動,那麼有可能兩個任務同時運行。 – svick