我对async
和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;
}
但上面的代码不会编译。它肯定在这里或那里缺少一些async
或await
个关键字。我也不知道如何编写Execute()
方法。你能帮忙吗?
答案 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);
}
}