请参阅以下示例.
public partial class MainWindow : Window { // . . . private async void startButton_Click(object sender,RoutedEventArgs e) { // ONE Task<int> getLengthTask = AccessTheWebAsync(); // FOUR int contentLength = await getLengthTask; // SIX resultsTextBox.Text += String.Format("\r\nLength of the downloaded string: {0}.\r\n",contentLength); } async Task<int> AccessTheWebAsync() { // TWO HttpClient client = new HttpClient(); Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com"); // THREE string urlContents = await getStringTask; // FIVE return urlContents.Length; } }
根据我收集的内容,在上面的代码中,AccessTheWebAsync()被同步调用(即,在调用时,控件不会立即返回).但是在名为“THREE”的行中,运行时将返回控件.
我的问题是:
>运行时如何决定何时使用线程池或何时在调用线程中运行任务? (即执行代码而不返回控制)
>在上面的代码中,将使用新线程(或线程池)?
>如果AccessTheWebAsync()执行计算密集型操作,例如运行具有无数次迭代的循环,则控件将仅在循环完成时返回到调用者.是对的吗?
>在异步函数中,有没有办法立即返回控件,然后继续在后台线程中执行工作? (就像我们调用threadpool.queueuserworkitem())
>在没有await的情况下调用异步方法(假设它可能)与调用非异步方法相同吗?
解决方法
问题1:我在这里引用MSDN:
The async and await keywords don’t cause additional threads to be created. Async methods don’t require multithreading because an async method doesn’t run on its own thread.
问题2:可能在GetStringAsync的实现中,但我们不知道,我们也不必知道它.这足以让我们知道GetStringAsync以某种方式得到它的结果而不会阻塞我们的线程.
问题3:如果循环放在await关键字之前,是的.
问题4:引用与以前相同的段落:
You can use Task.Run to move cpu-bound work to a background thread
您不需要async和await关键字.例:
private Task<int> DoSomethingAsync() { return Task.Run(() => { // Do cpu heavy calculation here. It will be executed in the thread pool. return 1 + 1; }); }
问题5:我会再次引用
An async method typically contains one or more occurrences of an await operator,but the absence of await expressions doesn’t cause a compiler error. If an async method doesn’t use an await operator to mark a suspension point,the method executes as a synchronous method does,despite the async modifier. The compiler issues a warning for such methods.
Source(和以前一样,只是一个不同的部分)