what do I do if I meet, for instance, following situation: my class is a wrapper around some third-party class and will have to invoke an async method from the wrapped class inside my Dispose? (see the code below). Of course I will implement IAsyncDisposable.
But Microsoft recommends disposables to be able to be disposed from their finalizers
And my question is how do I do it here?
In the documentation example the async-disposable-only object (_asyncDisposableResource) is not disposed in case of disposal from finalizer, if it doesn't support IDisposable as well.
btw they say it's better not to support synchronous pairs for async method: see here , so this situation is pretty likely.
public class MyWrapperForTheRepository: IAsyncDisposable
{
private ThirdPartyRepository _wrappedRepository = new ThirdPartyRepository();
public void MakeSomeChanges() => _wrappedRepository.MakeSomeChanges();
public async ValueTask DisposeAsync()
{
await _wrappedRepository.SaveAllTheChangesAsync();
_wrappedRepository = null;
}
~MyWrapperForTheRepository()
{
?????????????????????
}
}
CodePudding user response:
But Microsoft recommends disposables to be able to be disposed from their finalizers
Not at all. In fact, finalizers should not call (the parameterless) Dispose()
, and they should not call DisposeAsync()
either.
Finalizers are only for disposing unmanaged resources. Personally, I recommend that every type either have unmanaged resources or managed resources, and never both. The resulting code is much cleaner than following the Dispose(bool disposing)
pattern.