为什么我更喜欢使用API​​异步功能而不是用Task.Run包装同步功能? [英] Why should I prefer using API async fucntions over wrapping synchronous ones with Task.Run?

查看:100
本文介绍了为什么我更喜欢使用API​​异步功能而不是用Task.Run包装同步功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这段代码之间是有区别的:

I know there is a difference between this code:

var streamWriter = new StreamWriter("something.txt");
streamWriter.WriteAsync("text");

和这个:

var streamWriter = new StreamWriter("something.txt");
Task.Run(()=> streamWriter.Write("text"));

第一个更有意义.

在等待结果的另一种情况下,此代码:

and in different scenario when I am awaiting a result, this code:

var streamReader = new StreamReader("something.txt")
char[] chars = new char[10];

Task<int> task = streamReader.ReadAsync(chars, 0, chars.Length);
//Do something...

int num = await task;
//Do something with num...

比这更有意义:

var streamReader = new StreamReader("something.txt")
char[] chars = new char[10];

Task<int> task = Task.Run(()=>streamReader.Read(chars, 0, chars.Length));
//Do something...

int num = await task;
//Do something with num...

我猜想,内置的异步API的使用不仅在清晰度上更好,而且实际上比没有原因地等待ThreadPool线程更好,更有效地管理了ThreadPool线程.

I guess the use of the built in async API is better not only in clarity and it actually manages the ThreadPool threads better and in more efficient way than having a ThreadPool thread waiting for no reason.

对吗?

推荐答案

包装在Task.Run中的同步调用将在该操作期间阻止线程池线程.真正的异步实现不会.

A synchronous call wrapped in a Task.Run will block a thread pool thread for the duration of that operation. A truly asynchronous implementation will not.

尤其对于流而言,确定操作是否真正异步"可能有些棘手.例如,如果将特殊标志传递给它们的构造函数,则网络流总是真正异步的,内存流永远不是真正的异步的,文件流只是真正异步的.

With streams in particular, whether the operation is "truly asynchronous" can be a bit tricky to determine. For example, network streams are always truly asynchronous, memory streams are never truly asynchronous, and file streams are only truly asynchronous if you pass a special flag to their constructor.

这篇关于为什么我更喜欢使用API​​异步功能而不是用Task.Run包装同步功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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