简体   繁体   English

存储库是否应返回Task <SomeEntity> ?

[英]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.

相关问题 此代码是否应返回任务或任务 <object> ? - Should this code return a Task or Task<object>? 返回 Task 的方法应该抛出异常吗? - Should methods that return Task throw exceptions? 我为什么要返回任务<iactionresult>在 Controller 中?</iactionresult> - Why should I return Task<IActionResult> in a Controller? 我应该将任务包装在另一个任务中还是应该返回创建的任务? - Should I wrap a task in another task or should I just return the created task? 应该返回Task的API中的方法是否以Task或Async结尾 - Should methods in an API that return Task end with Task or Async 为什么某些返回任务的方法在通用存储库模式中未标记为异步 - Why are some methods that return a Task not marked as Async in generic repository pattern 存储库应该引发自定义异常还是返回状态类型? - Should a repository throw custom exceptions or return a status type? 存储库层是否应该返回数据传输对象(DTO)? - Should the repository layer return data-transfer-objects (DTO)? 如果我将 async 关键字添加到应该返回 Task 的方法中,它会将返回值包装在 Task 中? - If i add async keyword to a method which which should return a Task it wrap the return value in Task? 我应该如何从存储库返回自定义结果集? - How should I return custom result sets from repository?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM