Task.Run 作为反模式?
Task.Run as an anti-pattern?
我正在为我的 WinRT 项目使用 SQLite.NET PCL 库
SQliteAsyncConnection
class,提供 classic SQLiteConnection
方法的异步版本。但是,在项目的 Github page 中说明如下:
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
被视为反模式?这允许开发人员准确地实现他需要的目标 - 运行 在单独的线程上访问数据库代码,同时应用程序保持对用户输入的响应。每次手动编写 Task.Run
片段而不使用 class 的异步版本会更好吗?
这种模式的潜在问题和挫折是什么?
是的。如果库的使用者明确声明他想将该工作卸载到不同的线程会更好(如果这种情况不止一次发生,他们可以像库一样拥有辅助方法)。
否则他们可能会认为此方法本质上是异步的。事实并非如此,除非您可以查看源代码,否则您无法知道。
可以在 Should I expose asynchronous wrappers for synchronous methods? 中找到更长的解释。具体来说:
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.
我正在为我的 WinRT 项目使用 SQLite.NET PCL 库
SQliteAsyncConnection
class,提供 classic SQLiteConnection
方法的异步版本。但是,在项目的 Github page 中说明如下:
Please be aware that the
Task.Run
pattern used inSQLiteAsyncConnection
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
被视为反模式?这允许开发人员准确地实现他需要的目标 - 运行 在单独的线程上访问数据库代码,同时应用程序保持对用户输入的响应。每次手动编写 Task.Run
片段而不使用 class 的异步版本会更好吗?
这种模式的潜在问题和挫折是什么?
是的。如果库的使用者明确声明他想将该工作卸载到不同的线程会更好(如果这种情况不止一次发生,他们可以像库一样拥有辅助方法)。
否则他们可能会认为此方法本质上是异步的。事实并非如此,除非您可以查看源代码,否则您无法知道。
可以在 Should I expose asynchronous wrappers for synchronous methods? 中找到更长的解释。具体来说:
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.