async(C# 参考)
async(C# 参考)
C#
public async Task<int> ExampleMethodAsync() { // . . . . } 如果不熟悉异步编程,或者不了解异步方法如何在不阻止调用方线程的情况下使用? string contents = await httpClient.GetStringAsync(requestUrl);
异步方法同步运行,直至到达其第一个? 如果?
示例下面的示例展示了异步事件处理程序? 可以在 Visual Studio 中将此代码作为 Windows Presentation Foundation (WPF) 应用或 Windows 应用商店应用运行。?需要一个名为?
XAML
" style="box-sizing: inherit; font-family: SFMono-Regular,monospace; font-size: 1em; direction: ltr; position: relative; border: 0px; padding: 0px; display: block; line-height: 19px;"><Button Content="Button" HorizontalAlignment="Left" Margin="88,77,0" VerticalAlignment="Top" Width="75" Click="StartButton_Click" Name="StartButton"/> <TextBox HorizontalAlignment="Left" Height="137" Margin="88,140,0" TextWrapping="Wrap" Text="<Enter a URL>" VerticalAlignment="Top" Width="310" Name="ResultsTextBox"/> 将代码作为 WPF 应用运行:
将此代码作为 Windows 应用商店应用运行:
private async void StartButton_Click(object sender,RoutedEventArgs e) { // ExampleMethodAsync returns a Task<int>,which means that the method // eventually produces an int result. However,ExampleMethodAsync returns // the Task<int> value as soon as it reaches an await. ResultsTextBox.Text += "n"; try { int length = await ExampleMethodAsync(); // Note that you could put "await ExampleMethodAsync()" in the next line where // "length" is,but due to when ‘+=‘ fetches the value of ResultsTextBox,you // would not see the global side effect of ExampleMethodAsync setting the text. ResultsTextBox.Text += String.Format("Length: {0:N0}n",length); } catch (Exception) { // Process the exception if one occurs. } } public async Task<int> ExampleMethodAsync() { var httpClient = new HttpClient(); int exampleInt = (await httpClient.GetStringAsync("http://msdn.microsoft.com")).Length; ResultsTextBox.Text += "Preparing to finish ExampleMethodAsync.n"; // After the following return statement,any method that‘s awaiting // ExampleMethodAsync (in this case,StartButton_Click) can get the // integer result. return exampleInt; } // The example displays the following output: // Preparing to finish ExampleMethodAsync. // Length: 53292
?重要 若要深入了解各项任务以及在等待任务期间所执行的代码,请参阅使用 async 和 await 的异步编程。?有关使用类似元素的完整 WPF 示例,请参阅演练:使用 Async 和 Await 访问 Web。 返回类型异步方法可具有以下返回类型:
此异步方法既不能声明任何?in、ref?或?out?参数,也不能具有引用返回值,但它可以调用具有此类参数的方法。 如果异步方法的 语句指定一个 类型的操作数,则应指定? 你应主要使用? 从 C# 7.0 开始,返回另一个类型(通常为值类型),该类型具有? 有关详细信息和示例,请参阅异步返回类型。 请参阅(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |