In .net 4.5, there are new keyword, which are await and async. which is used widely in the asynchronous programming.
In this post we are going to examining in the language level , what is the requirement on the return types on await calls and the async method. (can we have async dynamic method? I guess yes, but will need to verify that).
You can find the original discussion on the return types of such async/await method in the Async Return Types.
Most of the code is a reinvigorate of the sample code that you can find from Async Return Types. but with my own comment and annotation..
namespace AsyncResturnTypes
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
// -- Void Return example
private async void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Clear();
// Start the process and await its completion. DriverAsync is a
// Task-returning async method.
await DriverAsync();
// Say goodbye.
textBox1.Text += "\r\nAll done, exiting button-click event handler.";
}
async Task DriverAsync()
{
// Task<T>
// Call and await the Task<T>-returning async method in the same statement.
int result1 = await TaskOfT_MethodAsync();
// call and await in separate statements
Task<int> integerTask = TaskOfT_MethodAsync();
// You can do other work that does not rely on integerTask before awaiting.
textBox1.Text += String.Format("Application can continue working while the Task<T> runs. . . . \r\n");
int result2 = await integerTask;
// Display the values of the result1 variable, the result2 variable, and
// the integerTask.Result property.
textBox1.Text += String.Format("\r\nValue of result1 variable: {0}\r\n", result1);
textBox1.Text += String.Format("Value of result2 variable: {0}\r\n", result2);
textBox1.Text += String.Format("Value of integerTask.Result: {0}\r\n", integerTask.Result);
// Task
// Call and await the Task-returning async method in the same statement.
await Task_MethodAsync();
// Call and await in separate statements.
Task simpleTask = Task_MethodAsync();
// You can do other work that does not rely on simpleTask before awaiting.
textBox1.Text += String.Format("\r\nApplication can continue working while the Task runs. . . .\r\n");
await simpleTask; // -- Async methods that don't contain a return statement or that contain a return statement that doesn't return an operand usually have a return type of Task. Such methods would be void-returning methods
}
// TASK<T> EXAMPLE
async Task<int> TaskOfT_MethodAsync()
{
// The body of the method is expected to contain an awaited asynchronous
// call.
// Task.FromResult is a placeholder for actual work that returns a string.
var today = await Task.FromResult<string>(DateTime.Now.DayOfWeek.ToString()); // as in the "TASK EXAMPLE" case, you will need to have at least some await call somewhere and it shall be covered by all cases.
// The method then can process the result in some way.
int leisureHours;
if (today.First() == 'S')
leisureHours = 16;
else
leisureHours = 5;
// Because the return statement specifies an operand of type int, the
// method must have a return type of Task<int>.
return leisureHours; // -- the C# runtime has this weaven ability, though you were returning this "int" result, it will wraps and return such an Task<int> types to match with the prototypes..
}
// TASK EXAMPLE
async Task Task_MethodAsync()
{
// The body of an async method is expected to contain an awaited
// asynchronous call.
// Task.Delay is a placeholder for actual work.
await Task.Delay(2000); // if the containing method is "void" , you will see compiling errors.
// so it is a prerequisite to have this await method.
// Task.Delay delays the following line by two seconds.
textBox1.Text += String.Format("\r\nSorry for the delay. . . .\r\n");
// This method has no return statement, so its return type is Task.
}
}
and this is the xaml code files.
<Window x:Class="AsyncResturnTypes.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<!-- source code from : Async Return types...
http://msdn.microsoft.com/en-us/library/vstudio/hh524395.aspx
-->
<Grid>
<Button x:Name="button1" Content="Start" HorizontalAlignment="Left" Margin="214,28,0,0" VerticalAlignment="Top" Width="75" HorizontalContentAlignment="Center" FontWeight="Bold" FontFamily="Aharoni" Click="button1_Click"/>
<TextBox x:Name="textBox1" Margin="0,80,0,0" TextWrapping="Wrap" FontFamily="Lucida Console"/>
</Grid>
</Window>

本文探讨了C# 4.5中引入的async和await关键字,并通过实例演示了如何正确使用这些特性来提高应用程序的响应性和效率。文章还详细介绍了不同返回类型的方法在异步编程中的应用。
744

被折叠的 条评论
为什么被折叠?



