我正在等待/ Async和CancellationTokens。我的代碼有效,但是當它被取消時,Task發生了什麼?它仍然佔用資源,或者是垃圾收集還是什麼?取消任務時會發生什麼?
這裏是我的代碼:
private CancellationTokenSource _token = new CancellationTokenSource();
public Form1()
{
InitializeComponent();
}
async Task<String> methodOne()
{
txtLog.AppendText("Pausing for 10 Seconds \n");
var task = Task.Delay(10000, _token.Token);
await task;
return "HTML Returned. \n";
}
private async void button1_Click(object sender, EventArgs e)
{
try
{
var task1 = methodOne();
await task1;
txtLog.AppendText(task1.Result + "\n");
txtLog.AppendText("All Done \n");
}
catch (OperationCanceledException oce)
{
txtLog.AppendText("Operation was cancelled");
}
}
private void button2_Click(object sender, EventArgs e)
{
_token.Cancel();
}