using asynchronous call within IDisposable.Dispose()
.net, asynchronous, c#
Solution
You can only use `await` when the method returns `Task`, `Task<T>` or another implementation of an awaitable.
`IDisposable` does not define a `Task Dispose()` method. You can always write your own, but it will not be called when you exit the `using` block.
Depending on the locking mechanism in your resource, you may risk race conditions with an `async void` (avoid those!).
Problem
I needed to implement a simple transaction. For that case my transaction class implements the IDisposable interface. That way I can use my transaction class within a using statement and if any error happens within that scope, everything get's rolled back when the transaction is disposed. ``` using (var transaction = new Transaction()) { // do some stuff } ``` The "do some stuff" also includes some client/server connections etc. Now I roll back everything if "do some stuff" raised any error. ``` public async void Dispose(){ // roll back everything on error } ``` That probably includes to cleanup some resources on a server where I need to call asynchronous operations. That leads to my question: can I safely just use the async keyword for my Dispose() implementation to enable the await keyword within its implementation? Or could this lead probably to race conditions due to synchronisation context issues or something like that?