I have the following two basic helper methods and I am calling these two methods from my “Thread Sleep” and “Task Delay” button.void PutThreadSleep(){ Thread.Sleep(5000);} async Task PutTaskDelay(){ await Task.Delay(5000, tokenSource.Token);} private void btnThreadSleep_Click(object sender, EventArgs e){ PutThreadSleep(); MessageBox.Show("I am back");} private async void btnTaskDelay_Click(object sender, EventArgs e){ await PutTaskDelay(); MessageBox.Show("I am back");}asically there is nothing to describe about the code up there (I am not going to explain what async and await here, you can find many articles in MSDN and one of myprevious postexplaining async/await). When I clicked both these buttons, the message boxes will be displayed after 5 seconds. But there are significant differences between these two ways. Let’s find out what.CancellationTokenSource tokenSource = new CancellationTokenSource(); async Task PutTaskDelay(){ try { await Task.Delay(5000, tokenSource.Token); } catch (TaskCanceledException ex) { } catch (Exception ex) { }}Here when the task got cancelled, it will be throwing me aTaskCanceledException.I am just catching the exception and suppressing it, because don't want to show any message about that.So in my “Cancel Task Delay” button click event, I am asking the task to be cancelled.
private void btnCancelTaskDelay_Click(object sender, EventArgs e){ tokenSource.Cancel();}Once the task has been cancelled, the control returns immediately to the next line and message box will be shown.
https://code.msdn.microsoft.com/ThreadSleep-vs-TaskDelay-766b46b7
~7F9TGWWHT`]6.png)
新聞熱點
疑難解答