存储库应该 return 任务 <SomeEntity> 吗?
Should a repository return Task<SomeEntity>?
我正在设计一个存储库,但我有这个疑问。
我应该将其设计为阻塞操作还是异步?
我倾向于认为阻塞更优雅,因为用户可以在需要时使用诸如
之类的方式将调用包装为异步
Task.Run( () => repository.Get(...));
你怎么看?
由于底层数据源在大多数情况下自然是异步的(网络服务、数据库、文件),async
API 是首选方式。
blocking is more elegant, since users can wrap calls to be async when needed
实际上,反之亦然
如果需要,用户 (not you!) 可以将异步调用包装到同步调用中:
Task<MyObj> DoSomethingAsync() { ... }
MyObj DoSomething()
{
return DoSomethingAsync().Result;
}
同时:
Task.Run( () => repository.Get(...));
被称为"async over sync",必须避免:
should we expose an asynchronous entry point for a method that’s
actually synchronous? The stance we’ve taken in .NET 4.5 with the
Task-based Async Pattern is a staunch “no.”
我正在设计一个存储库,但我有这个疑问。
我应该将其设计为阻塞操作还是异步?
我倾向于认为阻塞更优雅,因为用户可以在需要时使用诸如
之类的方式将调用包装为异步Task.Run( () => repository.Get(...));
你怎么看?
由于底层数据源在大多数情况下自然是异步的(网络服务、数据库、文件),async
API 是首选方式。
blocking is more elegant, since users can wrap calls to be async when needed
实际上,反之亦然
如果需要,用户 (not you!) 可以将异步调用包装到同步调用中:
Task<MyObj> DoSomethingAsync() { ... }
MyObj DoSomething()
{
return DoSomethingAsync().Result;
}
同时:
Task.Run( () => repository.Get(...));
被称为"async over sync",必须避免:
should we expose an asynchronous entry point for a method that’s actually synchronous? The stance we’ve taken in .NET 4.5 with the Task-based Async Pattern is a staunch “no.”