使用声明,呼吁异步方法 [英] Calling asynchronous method in using statement

查看:151
本文介绍了使用声明,呼吁异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

欲使用异步呼叫来发送消息,但一次性的资源中的方法中使用。我不知道如何正确地处理这个问题。

 使用(IDisposable的disposeMe =新DisposableThing())
{
    MethodAsync(disposeMe);
}

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

编辑:

根据建议由@Servy接受的答案。实施已更改为:

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


解决方案

  

异步方法没有任何回调


嗯,这是一个问题。 A 非常大的的问题。如果可能的话,你应该解决这个问题;除非有很好的理由不,所有的异步方法提供的部分的指呼叫者知道什么时候他们已经完成,无论是回调,返回一个任务,触发一个事件,等,这是因为这是依赖于一次性的资源做到这一点异步方法特别麻烦。

如果你真的有没有当操作完成被通知的方式,那么有没有办法让你叫的Dispose 方法完成后。唯一意味着你必须确保你不处置的资源,而异步操作仍需要很泄漏资源并没有处置它。如果一次性资源具有一个终结它可能会最终被清理,但不是所有的一次性资源这样做。

如果您的可以的修改异步方法不知何故,那么你只需要调用的Dispose 回调,还是在任务的延续,或在相关事件的处理程序。您将不能够使用使用除非你能等待的异步操作(因为等待只是真棒这样)。

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

这篇关于使用声明,呼吁异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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