Why should I prefer using API async fucntions over wrapping synchronous ones with Task.Run?

别等时光非礼了梦想. 提交于 2019-12-11 04:45:51

问题


I know there is a difference between this code:

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

and this:

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

the first one makes much more sense.

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...

makes much more sense than this:

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...

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.

Is it right?


回答1:


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.



来源:https://stackoverflow.com/questions/39669064/why-should-i-prefer-using-api-async-fucntions-over-wrapping-synchronous-ones-wit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!