0

我对asyncand的概念还很陌生await。现在我有这样的东西:

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()方法。你能帮我吗?

4

1 回答 1

1

首先,要await在 lambdas 中使用,您必须使用修饰符来装饰它们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);
    }
}
于 2013-08-02T07:17:10.173 回答