I have a component, which can perform long async actions and can be destroyed before that actions are completed. In that case, I want just to stop running that actions and forget about them, without any exceptions. I have the next example:
private CancellationTokenSource destroyTokenSource = new CancellationTokenSource();
private async void RunExample()
{
await LongAction().MuteOnDestroy(destroyTokenSource.Token);
// ... actions that should not be performed with destroyed object
}
private async Task<bool> LongAction()
{
// some very long actions
return true;
}
// ...
public static class TaskExtension
{
public static Task<T> MuteOnDestroy<T>(this Task<T> task, CancellationToken destroyToken)
{
var promise = new TaskCompletionSource<T>();
task.ContinueWith(t =>
{
if (!destroyToken.IsCancellationRequested)
{
switch (t.Status)
{
case TaskStatus.Canceled:
promise.SetCanceled();
break;
case TaskStatus.Faulted:
promise.SetException(t.Exception!);
break;
case TaskStatus.RanToCompletion:
promise.SetResult(t.Result);
break;
}
}
}, TaskContinuationOptions.ExecuteSynchronously);
return promise.Task;
}
}
I have an assumption that the async method (in this example RunExample
method) that never completes (destroyToken.IsCancellationRequested == true
) can cause memory leaks but I am not sure because I don't know where the continuation of "forever waiting" method is stored.
Can it cause memory leaks?