我在玩 Await/Async 和 CancellationTokens。我的代码有效,但是当它被取消时任务会发生什么?它仍然占用资源还是垃圾收集或什么?
这是我的代码:
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();
}