Reputation: 307
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);
}
Upvotes: 1
Views: 242
Reputation: 1904
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#.
Upvotes: 2
Reputation: 40878
It is safe in that control will always return back to the instance of the method that created it. So as long as you:
using
statement or call Dispose()
manually, andawait
the callThen 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.
Upvotes: 4