对于每个方法,我希望创建Sync和Async,但不复制代码。如果我调用一个带有其他异步方法的异步方法,它是正确的代码吗?
public void MethodA(){//1
MethodAAsync().GetAwaiter();
}
public void MethodA(){//2 is it a correct code
MethodB();
MethodC();
...code
...code
...code
MethodD();
MethodE();
}
public async Task MethodAAsync(){
await MethodBAsync(cancellationToken);
await MethodCAsync(cancellationToken);
...code
...code
...code
await MethodDAsync(cancellationToken);
await MethodEAsync(cancellationToken);
}
//1 or 2发布于 2020-09-02 04:54:47
Synchronous wrappers for asynchronous methods is an antipattern。首先,我建议您只支持异步API。但有时这是不可能的,例如,出于向后兼容性的原因。
在这种情况下,我推荐使用boolean argument hack,它看起来像这样:
public void MethodA() {
MethodACore(sync: true).GetAwaiter().GetResult();
}
public Task MethodAAsync() {
return MethodACore(sync: false);
}
private async Task MethodACore(bool sync) {
if (sync) MethodB(); else await MethodBAsync(cancellationToken);
if (sync) MethodC(); else await MethodCAsync(cancellationToken);
...code
...code
...code
if (sync) MethodD(); else await MethodDAsync(cancellationToken);
if (sync) MethodE(); else await MethodEAsync(cancellationToken);
}https://stackoverflow.com/questions/63670515
复制相似问题