Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling asynchronous method in using statement

I want to send a message using an asynchronous call but disposable resources are used in the process. I'm not sure how to properly handle this.

using(IDisposable disposeMe = new DisposableThing())
{
    MethodAsync(disposeMe);
}

Any ideas how to do this. The async method does not have any callback.

EDIT:

Based on the suggestion the accepted answer by @Servy. The implementation was changed to:

public async Task Method()
{
    using(IDisposable disposeMe = new DisposableThing())
    {
        await MethodAsync(disposeMe);
    }
}
like image 633
Brian Triplett Avatar asked Dec 06 '13 18:12

Brian Triplett


People also ask

What happens when you call an async method?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

How do you make a synchronous call asynchronous?

The simplest way to execute a method asynchronously is to start executing the method by calling the delegate's BeginInvoke method, do some work on the main thread, and then call the delegate's EndInvoke method. EndInvoke might block the calling thread because it does not return until the asynchronous call completes.

How do you use asynchronous?

If you use the async keyword before a function definition, you can then use await within the function. When you await a promise, the function is paused in a non-blocking way until the promise settles. If the promise fulfills, you get the value back. If the promise rejects, the rejected value is thrown.


1 Answers

The async method does not have any callback

Well that's a problem. A very big problem. If at all possible you should fix that; unless there is a very good reason not to, all asynchronous methods should provide some means for the caller to know when they have completed, whether it's a callback, returning a Task, firing an event, etc. It's particularly troubling for an asynchronous method that is dependent on a disposable resource to do this.

If you really do have no way of being notified when the operation completes, then there is no way for you to call Dispose after the method completes. The only means you have of ensuring you don't dispose of the resource while the async operation still needs it is to leak the resource and not dispose of it at all. If the disposable resource has a finalizer it's possible it will be cleaned up eventually, but not all disposable resources do so.

If you can modify the asynchronous method somehow then you simply need to call Dispose in the callback, or in a continuation of the task, or in a handler of the relevant event. You won't be able to use a using unless you can await the asynchronous operation (because await is just awesome like that).

like image 188
Servy Avatar answered Sep 25 '22 19:09

Servy