I have a class with a resource that ideally should be disposed of using an async method, and I'm trying to use a Using statement to do so.
Luckily, .NET added the IAsyncDisposable interface as well as a nice doc explaining how to Implement a DisposeAsync method. The doc says:
The
publicparameterlessDisposeAsync()method is called implicitly in anawait usingstatement
Easy! Except... there's just one problem: I'm using VB.NET, not C#. I can't find any documentation on how to use this feature in VB.NET, or anyone asking after it. VB.NET (using .NET 6) will only allow a Using statement for an instance of IDisposable, and if both IDisposable and IAsyncDisposable are implemented, it only calls Dispose, not DisposeAsync. I can't find any equivalent Await Using statement for VB.NET.
Is there any way for me to properly leverage the IAsyncDisposable interface in VB.NET with a Using statement? Or have I finally reached the point where Microsoft's abandonment of the language has caught up with me?
 
                        
IAsyncDisposableinUsing.AwaitinsideFinally.Approach 1: Use C# for the
usingpart:Just create a new empty C# Class Library project with a single helper method which you can call from VB.NET, something like this:
(Just don't expect to be able to use
ConfigureAwait(False)- even in C# it's hard).Then call it from VB.NET:
An alternative way of implementing this method, without using any C# step, is to use Reflection.Emit from within VB.NET to generate equivalent (and safe) IL that reimplements that
UsingAsyncDisposableAsyncmethod - though this will be a lot of work for probably little gain tbh.Approach 2: Embrace VB.NET's verbosity
Instead of using any C# code, we can actually still do it all in VB.NET, with the caveat that you need to use
Try/Catchand notTry/Finallyas VB.NET still can't useAwaitinsideFinally:I haven't run this code through any static-analysis, but I'm confident this won't trigger CA2000