为什么我更喜欢使用API​​异步功能而不是使用Task.Run包装同步功能?

时间:2016-09-23 20:31:13

标签: c# asynchronous async-await task-parallel-library threadpool

我知道此代码之间存在差异:

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

和此:

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

第一个更有意义。

在我等待结果的不同场景中,这段代码:

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线程无缘无故地更有效地管理public function parse_date($text, $offset, $length){ $parseArray = preg_split( "/[\s,.]/", $text); $dateTest = implode(" ", array_slice($parseArray, $offset, $length == 0 ? null : $length)); $date = strtotime($dateTest); if ($date){ return $date; } //make the string one word shorter in the front $offset++; //have we reached the end of the array? if($offset > count($parseArray)){ //reset the start of the string $offset = 0; //trim the end by one $length--; //reached the very bottom with no date found if(abs($length) >= count($parseArray)){ return false; } } //try to find the date with the new substring return $this->parse_date($text, $offset, $length); } 线程。

是不是?

1 个答案:

答案 0 :(得分:4)

包含在Task.Run中的同步调用将在该操作期间阻塞线程池线程。一个真正的异步实现will not

特别是对于流,操作是否真正异步&#34;确定可能有点棘手。例如,网络流始终是真正的异步,内存流永远不是真正的异步,如果你将特殊标志传递给它们的构造函数,文件流才是真正的异步。