简体   繁体   中英

C# recursion with disposable parameter and async await

Is it safe to call a async method recursively if the method contains parameters that need to be disposed?

public async Task<bool> ConnectAsync(CancellationTokenSource cancellationTokenSource)
{
    using CancellationTokenSource token = new CancellationTokenSource();
    await ConnectAsync(token).ConfigureAwait(false);
}

It is safe in that control will always return back to the instance of the method that created it. So as long as you:

  1. Use a using statement or call Dispose() manually, and
  2. await the call

Then the object will get disposed properly, and not before it's used.

However, as with all recursion, you need to be careful not to end up in a stack overflow . That method, exactly as you have written it, will end up in a stack overflow.

Yes, in C# recursion with using statement is safe, the object will be disposed properly when the execution of the callee terminates and code gets back to the caller.

But as I understand you want an infinite recursion, in that case that object will never be disposed, not because your code is unsafe, simply it is not possible to dispose that object.

Anyway, the problem there is that you can't do infinite recursion, soon or after you will deal with a stack overflow, c# doesn't support tail optimization, so infinite recursion is not supported in C#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM