Task.Run作为一个反模式? [英] Task.Run as an anti-pattern?

查看:235
本文介绍了Task.Run作为一个反模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在用的是SQLite.NET PCL库我的WinRT项目的 SQliteAsyncConnection 类,它提供了经典的 SQLiteConnection 方法异步版本。然而,对项目的 Github上页以下是说:

I am using the SQLite.NET PCL library for my WinRT projects with the SQliteAsyncConnection class, which offers async versions of the classic SQLiteConnection methods. However, on the project's Github page the following is stated:

请注意,用于 Task.Run 模式    SQLiteAsyncConnection 可以被认为是反模式(库   不应该提供异步方法,除非他们是真正的异步)。本   类保持向后兼容性和使用情况   其中,异步隔离是很方便的。

Please be aware that the Task.Run pattern used in SQLiteAsyncConnection can be considered an anti-pattern (libraries should not provide async methods unless they are truly async). This class is maintained for backwards compatibility and for use-cases where async-isolation is handy

为什么在这种情况下,认为是一种反模式使用 Task.Run ?这使得开发人员能够准确地实现他所需要的目标 - 在一个单独的线程上运行的数据库访问code,而应用程序保持响应用户的输入。它会更好手动编写 Task.Run 片段每次而不是使用类的异步版本共?

Why is using Task.Run in this case considered an anti-pattern? This allows the developer to achieve exactly the goal he needs - to run the database access code on a separate thread while the app stays responsive to user input. Would it be better to manually write Task.Run snippet each time and not use the async version of the class altogether?

什么是这种模式的潜在问题和挫折?

What are the potential issues and setbacks of this pattern?

推荐答案

是的。这将是更好,如果消费者对库将明确规定,他要卸载的工作提高到一个不同的线程(如果出现不止一次,他们可以有一个辅助方法,就像图书馆有)。

Yes. It would be better if the consumer for the library will explicitly state that he wants to offload that work to a different thread (if that occurs more than once they can have a helper method just as the library has).

否则,他们可能会认为,这种方法本质上是异步的。这是不是这样的,你可以不知道,除非你可以看看源$ C ​​$ C。

Otherwise they might believe that this method is inherently asynchronous. Which is not the case and you can't know that unless you can look at the source code.

有一个较长的解释可以在找到我应该公开异步封装同步方法?。具体做法是:

A longer explanation could be found in Should I expose asynchronous wrappers for synchronous methods?. Specifically:

我认为应该暴露的唯一异步方法是那些在他们同步的同行可扩展性优势。异步方法不能完全暴露卸载的目的:这样的好处是可以很容易地通过使用对与同步方法以异步方式运行,如专门针对功能的同步方法,消费者可以实现Task.Run。

I believe the only asynchronous methods that should be exposed are those that have scalability benefits over their synchronous counterparts. Asynchronous methods should not be exposed purely for the purpose of offloading: such benefits can easily be achieved by the consumer of synchronous methods using functionality specifically geared towards working with synchronous methods asynchronously, e.g. Task.Run.

这篇关于Task.Run作为一个反模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆