将部分异步方法重构为lambda

时间:2013-08-02 07:00:07

标签: c# .net .net-4.5 async-await c#-5.0

我对asyncawait的概念相当陌生。现在我有这样的事情:

public async void DoSomething()
{
    using (var obj = new SomeClass())
    {
        await obj.SomeAction();
    }

    Done = true;
}

但是随着obj对象的创建和管理变得越来越复杂,我想将其重构为:

public async void DoSomething()
{
    Manager.Execute(obj =>
    {
        await obj.SomeAction();
    });

    Done = true;
}

但上面的代码不会编译。它肯定在这里或那里缺少一些asyncawait个关键字。我也不知道如何编写Execute()方法。你能帮忙吗?

1 个答案:

答案 0 :(得分:1)

首先,要在lambdas中使用await,您必须使用async修饰符来装饰它们,就像方法一样:

Func<Task<Foo>> asyncFooFactory = async () => await whatever;

然后Execute方法如下所示:

// instead of Task, you could use void, but then you can't await its completion,
// which could get handy later, depending on your use case
public static async Task Execute(Func<YourClass, Task> externalStuff)
{
    using (var obj = new YourClass()) // replace with your own initializer code
    {
        await externalStuff(obj);
    }
}