c# - 基础设施 - 同步和异步接口和实现?
问题描述
当实现一个库/基础设施时,这个 API 的用户想要同步和异步地使用代码,我读到混合同步和异步不是一个好主意(例如同步实现包括等待异步实现)。
所以显然同步和异步实现应该分开。
是否有一种优雅的方法可以避免同步和异步实现的代码(或更准确地说是“流”)重复,这显然会冒泡到整个调用层次结构?
interface IMyInterface
{
void Foo();
Task FooAsync();
}
class MyImplementation1 : IMyInterface
{
public void Foo()
{
OtherMethod1();
OtherMethod2();
OtherMethod3();
OtherMethod4();
}
public async Task FooAsync()
{
await OtherMethod1Async();
await OtherMethod2Async();
await OtherMethod3Async();
await OtherMethod4Async();
}
private void OtherMethod1() { /* may contain other sync calls */ }
private void OtherMethod2() { /* may contain other sync calls */ }
private void OtherMethod3() { /* may contain other sync calls */ }
private void OtherMethod4() { /* may contain other sync calls */ }
private async Task OtherMethod1Async() { /* may contain other async calls */ }
private async Task OtherMethod2Async() { /* may contain other async calls */ }
private async Task OtherMethod3Async() { /* may contain other async calls */ }
private async Task OtherMethod4Async() { /* may contain other async calls */ }
}
解决方案
根据您的逻辑,您仍然可以共享一些逻辑。但在不同的地方,它应该不同。
如果有帮助,您可以使用模板系统(如T4)生成代码。
推荐阅读
- c - 如何打印星号的递减模式,其中星号被 C 中的空格替换?
- reactjs - 如何解决将 windows 本地 reactjs 应用程序迁移到 Linux 时出现的错误?
- python - 如何创建一个函数,返回作为参数传递的单词的变位词列表,在预定义的词典中找到?
- python - 解决 sqrt 函数 Python 中的 TypeError 错误
- django - Django admin Filter Horizontal Widget对对象数量的限制
- regex - 收集重复的 2 组模式
- pandas - 从重采样中查找最高和最低的条数
- javascript - Javascript parseInt() 函数只能工作一次?
- ios - 从 S3 Bucket SwiftUI 下载公共 PDF 文件
- javascript - 有没有更有效的方法来编写我的 JS?