[英]Writing a wrapper for an async method
I have a TransactionOperator
class which exposes the following static async method: 我有一个TransactionOperator
类,它公开以下静态异步方法:
public static async Task<bool> ProcessTransactionAsync(Transaction transaction)
{
var someTransactionOperator = ...; // get appropriate operator
// some code here
bool success = await someTransactionOperator.Process(transaction);
// some more code
return bool;
}
Now, I want to provide a wrapper instance method in the Transaction
class. 现在,我想在Transaction
类中提供一个包装实例方法。 My question is, which would be the correct/recommended way of writing it? 我的问题是,哪种是正确/推荐的书写方式? I'm leaning towards #2 because it feels right , but I don't have any supporting arguments for that choice. 我倾向于#2,因为它感觉不错,但是对于这种选择,我没有任何支持的论据。
// Option 1
public bool ProcessAsync()
{
return TransactionOperator.ProcessTransactionAsync(this).Result;
}
// Option 2
public Task<bool> ProcessAsync()
{
return TransactionOperator.ProcessTransactionAsync(this);
}
// Option 3 (compiler warning because there's no 'await' operator)
public async Task<bool> ProcessAsync()
{
return TransactionOperator.ProcessTransactionAsync(this).Result;
}
// Option 4
public async Task<bool> ProcessAsync()
{
return await TransactionOperator.ProcessTransactionAsync(this);
}
Option 2 is the best option. 选项2是最佳选择。 Option 4 is logically equivalent but has more overhead. 选项4在逻辑上等效,但是开销更大。
Options 1 and 3 are flat-out wrong. 选项1和3完全错误。 They both block synchronously (even though option 3 is async
, it behaves synchronously). 它们都同步阻止(即使选项3是async
,它也可以同步运行)。 Exposing synchronous wrappers for asynchronous methods is not recommended . 不建议为异步方法公开同步包装器 。 Among other problems, you can cause deadlocks (as I explain on my blog). 除其他问题外,您还可能导致死锁 (正如我在博客中所解释的那样)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.