我环顾四周,在任何地方都找不到这个问题。
鉴于以下方法:
public TOut WithThing<TOut>(Func<T, TOut> func)
{
var thing = CreateThing();
thing.DoSomething();
return func(thing);
}
void
当我不想返回值时,我有一个等效的方法来包装上面的内容(它实际上是在调用WithThing<bool>
并且只是丢弃结果):
public void WithThing(Action<T> action)
{
WithThing(x =>
{
action(x);
return false;
});
}
我正在尝试创建上述方法的异步版本,因为“事物”具有同步和异步方法。
我认为第一种方法的等价物是:
public async Task<TOut> WithThing<TOut>(Func<T, Task<TOut>> func)
{
var thing = CreateThing();
await thing.DoSomethingAsync().ConfigureAwait(false);
return await func(thing).ConfigureAwait(false);
}
我不认为我需要ConfigureAwait
's 但 Visual Studio 建议他们。这样对吗?为什么我需要ConfigureAwait
的?
如果上面的代码是正确的,那么我猜不返回值的等价物的签名将是public async Task WithThing(Func<T, Task> func)
. 身体会是什么?
请注意,使用ConfigureAwait(false)
是上下文相关的,您必须知道何时不使用它。请参阅ConfigureAwait FAQ和Async/Await - 异步编程中的最佳实践 - 配置上下文。
您对返回类型的猜测是正确的。
我会避免包装太多,因为它增加了分配和委托调用。
对于同步部分,我会做这样的事情:
public TOut WithThing<TOut>(Func<T, TOut> func)
{
Someting();
return func(thing);
}
public void WithThing(Action<T> action)
{
Someting();
action(x);
}
private void Someting()
{
var thing = CreateThing();
thing.DoSomething();
}
对于异步:
public async Task<TOut> WithThing<TOut>(Func<T, Task<TOut>> func)
{
await SometingAsync();
return await func(thing).ConfigureAwait(false);
}
public async Task WithThing(Func<Task> action)
{
await SometingAsync();
await action(thing).ConfigureAwait(false);
}
private void SometingAsync()
{
var thing = CreateThing();
await thing.DoSomethingAsync().ConfigureAwait(false);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句