在 using 语句中调用异步方法 [英] Calling asynchronous method in using statement

查看:34
本文介绍了在 using 语句中调用异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用异步调用发送消息,但在此过程中使用了一次性资源.我不确定如何正确处理这个问题.

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

任何想法如何做到这一点.异步方法没有任何回调.

根据建议,@Servy 接受了答案.实现更改为:

公共异步任务方法(){使用(IDisposable disposeMe = new DisposableThing()){等待 MethodAsync(disposeMe);}}

解决方案

异步方法没有任何回调

嗯,这是个问题.一个非常大的问题.如果可能的话,你应该解决这个问题;除非有很好的理由不这样做,否则所有异步方法都应该提供一些方法让调用者知道它们何时完成,是否是回调,返回一个Task,触发事件等.对于依赖一次性资源来执行此操作的异步方法尤其令人不安.

如果您确实无法在操作完成时收到通知,那么您将无法在方法完成后调用 Dispose.确保在异步操作仍然需要资源时不处理资源的唯一方法是泄漏资源并且根本不处理它.如果一次性资源有终结器,它可能最终会被清除,但并非所有一次性资源都这样做.

如果您可以以某种方式修改异步方法,那么您只需要在回调中,或在任务的延续中,或在处理程序中调用 Dispose相关事件.您将无法使用 using 除非您可以 await 异步操作(因为 await 就像那样很棒).

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);
    }
}

解决方案

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).

这篇关于在 using 语句中调用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆