小编典典

新的C#等待功能有什么作用?

c#

谁能解释该await功能的作用?


阅读 251

收藏
2020-05-19

共1个答案

小编典典

他们只是昨天在PDC上谈论了这一点

.NET中的Await与Tasks(并行编程)结合使用。.NET的下一版本中引入了该关键字。它或多或少使您可以“暂停”方法的执行以等待Task完成执行。这是一个简单的示例:

//create and run a new task  
Task<DataTable> dataTask = new Task<DataTable>(SomeCrazyDatabaseOperation);

//run some other code immediately after this task is started and running  
ShowLoaderControl();  
StartStoryboard();

//this will actually "pause" the code execution until the task completes.  It doesn't lock the thread, but rather waits for the result, similar to an async callback  
// please so also note, that the task needs to be started before it can be awaited. Otherwise it will never return
dataTask.Start();
DataTable table = await dataTask;

//Now we can perform operations on the Task result, as if we're executing code after the async operation completed  
listBoxControl.DataContext = table;  
StopStoryboard();  
HideLoaderControl();
2020-05-19