[英]Should a repository return Task<SomeEntity>?
I'm designing a repository, but I have this doubt. 我正在设计一个存储库,但是我有这个疑问。
Should I design it to be blocking operations or async? 我应该将其设计为阻止操作还是异步?
I tend to think that blocking is more elegant, since users can wrap calls to be async when needed with something like 我倾向于认为阻塞更为优雅,因为用户可以在需要时将调用包装为异步,例如
Task.Run( () => repository.Get(...));
What do you think? 你怎么看?
Since underlying data source is naturally asynchronous in most cases (web service, database, file), async
API is a preferred way. 由于底层数据源在大多数情况下(Web服务,数据库,文件)自然是异步的,因此首选
async
API。
blocking is more elegant, since users can wrap calls to be async when needed
阻塞更加优雅,因为用户可以在需要时将调用包装为异步
Actually, vice versa. 实际上,反之亦然。
User ( not you !) can wrap async call into synchronous one, if needed: 用户( 不是您 !)可以根据需要将异步调用包装为同步调用:
Task<MyObj> DoSomethingAsync() { ... }
MyObj DoSomething()
{
return DoSomethingAsync().Result;
}
while this: 而这:
Task.Run( () => repository.Get(...));
is called "async over sync" and must be avoided: 被称为“异步同步” ,必须避免:
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.”
我们在.NET 4.5中使用基于任务的异步模式采取的立场是坚定的“否”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.