I was toying with Await/Async and CancellationTokens. My code works, but what happens to the Task when it's Cancelled? Is it still taking up resources or is it garbage collected or what?
Here is my code:
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();
}
In the Task classes, cancellation involves cooperation between the user delegate, which represents a cancelable operation and the code that requested the cancellation. A successful cancellation involves the requesting code calling the CancellationTokenSource.Cancel method, and the user delegate terminating...
Task cancellation in C# and things you should know about it. The task mechanism in C# is a powerful beast in the area of parallel and concurrent programming. Controlling this beast may take lots of effort and pain. .NET Framework 4 introduces a convenient approach for cancellation of asynchronous operations.
A task that is canceled in this way transitions to the Canceled state, which the calling code can use to verify that the task responded to its cancellation request. The following example shows the basic pattern for task cancellation that throws the exception.
If you are waiting on a Task that transitions to the Canceled state, a System.Threading.Tasks.TaskCanceledException exception (wrapped in an AggregateException exception) is thrown. Note that this exception indicates successful cancellation instead of a faulty situation.
When a task is cancelled, it completes (in the cancelled state). It acts just like any other object in regards to garbage collection: if you have no references to it, it will be collected.
Note that although Task
does implement IDisposable
, you don't have to dispose it unless you're using the IAsyncResult.AsyncWaitHandle
member.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With