制作接口实现异步 [英] Making interface implementations async

查看:164
本文介绍了制作接口实现异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在试图让使用一些异步方法我的应用程序。
我所有的IO通过一个接口的明确实现做,我有点困惑如何使操作异步。

I’m currently trying to make my application using some Async methods. All my IO is done through explicit implementations of an interface and I am a bit confused about how to make the operations async.

在我看到的东西我已经在实施两个选项:

As I see things I have two options in the implementation:

interface IIO
{
    void DoOperation();
}

选项1:
做一个隐含的实现异步和等待结果隐含的实现。

OPTION1: Do an implicit implementation async and await the result in the implicit implementation.

class IOImplementation : IIO
{

     async void DoOperation()
    {
        await Task.Factory.StartNew(() =>
            {
                //WRITING A FILE OR SOME SUCH THINGAMAGIG
            });
    }

    #region IIO Members

    void IIO.DoOperation()
    {
        DoOperation();
    }

    #endregion
}

选项2:
做明确的执行异步和等待从隐含执行的任务。

OPTION2: Do the explicit implementation async and await the task from the implicit implementation.

class IOAsyncImplementation : IIO
{
    private Task DoOperationAsync()
    {
        return new Task(() =>
            {
                //DO ALL THE HEAVY LIFTING!!!
            });
    }

    #region IIOAsync Members

    async void IIO.DoOperation()
    {
        await DoOperationAsync();
    }

    #endregion
}

这些是实现优于其他的一个或有另一种方式去,我没有想到的?

Are one of these implementations better than the other or is there another way to go that I am not thinking of?

推荐答案

这些都不选项是正确的。你想实现异步同步接口。不要那样做。问题是,当 DoOperation()的回报,该操作将尚不完整。更糟的是,如果在操作过程中发生异常时(这是非常常见的有IO操作),用户将没有机会来处理该异常。

Neither of these options is correct. You're trying to implement a synchronous interface asynchronously. Don't do that. The problem is that when DoOperation() returns, the operation won't be complete yet. Worse, if an exception happens during the operation (which is very common with IO operations), the user won't have a chance to deal with that exception.

您需要做的是的修改界面的,所以它是异步的:

What you need to do is to modify the interface, so that it is asynchronous:

interface IIO
{
    Task DoOperationAsync(); // note: no async here
}

class IOImplementation : IIO
{
    public async Task DoOperationAsync()
    {
        // perform the operation here
    }
}

这样一来,用户将看到该操作是异步,他们将能够等待它。这也pretty多力量的code的用户切换到异步,但这是不可避免的。

This way, the user will see that the operation is async and they will be able to await it. This also pretty much forces the users of your code to switch to async, but that's unavoidable.

另外,我假设使用 StartNew()在您的实现只是一个例子,你不应该需要一个实现异步IO。 (和新建任务()更差,甚至不会工作,因为你没有开始()工作

Also, I assume using StartNew() in your implementation is just an example, you shouldn't need that to implement asynchronous IO. (And new Task() is even worse, that won't even work, because you don't Start() the Task.)

这篇关于制作接口实现异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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