asynchronous - 同步方法调用异步方法,里面有异步方法
问题描述
对于我想要创建同步和异步的每个方法,但不复制代码。如果我在内部调用带有其他异步方法的异步方法,它是正确的代码吗?
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
解决方案
异步方法的同步包装器是一种反模式。首先,我建议您只支持异步 API。但有时这是不可能的,例如,出于向后兼容性的原因。
在这种情况下,我建议使用布尔参数 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);
}
推荐阅读
- javascript - 如何在没有互联网的情况下进行重定向
- python - Tensorboard train data not same number of steps as validation data
- python-3.x - 在 sale.order.line 上过滤产品 - Odoo
- python - python中的复杂循环
- ruby - 为什么 Set#map 返回一个 Array 而不是另一个 Set?
- python - 将数据框转换为字典,不包括 ID
- node.js - 如何检查节点进程线程数
- graphviz - 带有自循环的graphviz状态机
- javascript - 在节点 js 中对 axios 请求的 Jest 测试
- javascript - 从 SharePoint 列表填充字段的最佳方式是什么?