`

C# 4.5 - the await and async return types

阅读更多

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 Typesbut 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>

 

分享到:
评论

相关推荐

    Effective C# 中文版---改善C#程序的50种方法

    8. **理解并使用异步编程**:C#的async/await关键字简化了异步编程,使得代码更易读,同时保持了非阻塞的特性。 9. **掌握LINQ(Language Integrated Query)**:LINQ提供了一种统一的查询接口,可用于操作各种数据...

    c# 关键字 微软官方文档

    - 如 async 和 await,用于编写异步方法。 - 在异步编程中,async 标识一个方法是异步的,而 await 则用于等待一个异步操作完成。 6. 查询关键字(Query Keywords): - 用于LINQ(语言集成查询)表达式的特定...

    C#高效编程改进C#代码的50个行之有效的办法( 第2版) 中文版

    《C#高效编程改进C#代码的50个行之有效的办法(第2版)》是一本专注于提升C#编程效率的专业书籍。本书的核心在于提供一系列实用的技巧和最佳实践,帮助开发者优化代码,提高软件开发的效率和质量。下面,我们将详细...

    S2 C# 指导学习3

    以上只是C#语言众多特性和概念中的一部分,实际上,C#还在不断发展,新的版本引入了更多现代编程特性,如async streams、pattern matching、nullable reference types等。学习C#不仅需要理解这些基础知识,还要关注...

    Illustrated C# 2010 源码

    6. **异步编程(Asynchronous Programming)**:C# 2010引入了`Task`类和`async/await`关键字,简化了异步编程模型,避免了回调地狱。如: ```csharp async Task&lt;string&gt; DownloadStringAsync(string url) { using ...

    C#7.0 NutShell_pdf档.rar

    - **异步编程**:async/await关键字,Task类,异步流。 - **并发与并行**:线程、线程池、锁、Monitor、Mutex、Semaphore、Task Parallel Library (TPL)。 - **内存管理与垃圾回收**:堆与栈、引用计数、垃圾回收...

    C# 9.0文档及编程指南中文版可编辑.rar

    - **异步编程**:学习使用async和await关键字进行异步操作,理解Task和Task。 - **泛型**:理解泛型的概念,如何创建泛型类、接口和方法,提高代码复用性。 - **元组**:学习使用元组进行数据打包和解包,以及...

    c#入门语法.docx

    这通常通过使用 `async` 和 `await` 关键字来实现。例如: ```csharp public async Task&lt;string&gt; DownloadDataAsync() { HttpClient client = new HttpClient(); string result = await client.GetStringAsync(...

    more Effective C# 改善C#的50个具体办法(中文版)

    12. **掌握async/await异步编程**:C# 5.0引入的异步编程模型,让程序在等待IO操作时不会阻塞线程。 13. **利用Task类进行并发编程**:Task表示一个异步操作,可以组合、控制和监视任务的执行,优化多任务管理。 ...

    Microsoft.Press.Microsoft.Visual.CSharp.2010.Step.by.Step.Mar.2010.rar

    《Microsoft Visual C# 2010 Step by Step》是由微软出版社出版的一本关于C#编程语言的入门教程,特别适合初学者和有一定基础的程序员使用。这本书详细介绍了C# 2010版本的新特性,并结合实际案例,通过逐步指导的...

    C#高级特性解析(整合)

    ### C#高级特性解析 C#作为一种现代的面向对象编程语言,在.NET框架的支持下提供了丰富的高级特性,这些特性不仅能够帮助开发人员编写出更加高效、简洁且易于维护的代码,还能够极大地提升软件项目的整体质量和开发...

    rx.net in action

    - **与异步编程的集成**:探讨Rx.NET如何与其他.NET异步编程技术相结合,如`async/await`等。 ##### 6. **第六章:Concurrency and Scheduling** - **并发和调度的基础**:介绍Rx.NET中处理并发和调度的基础知识,...

    练习3-C-Sharp

    C#通过async和await关键字支持异步编程,使得长时间运行的操作不会阻塞主线程,提高用户体验。 9. **.NET框架和库**: C#依赖于.NET框架,该框架包含大量预构建的类库,如System.IO用于文件操作,System.Net用于...

    Webapi 文件上传

    return supportedTypes.Contains(extension); } ``` 在前端,可以使用HTML5的`FormData`对象和`XMLHttpRequest`或`fetch` API来发送文件。下面是一个简单的JavaScript示例: ```html 上传 document....

    sendsms.rar_SendSms_sms

    return await response.Content.ReadAsStringAsync(); } ``` 确保在实际代码中替换`https://api.smsprovider.com/sms/send`为你的服务提供商的实际URL,并根据需要添加认证信息。 3. **使用SDK**:一些提供商提供...

    C-Sharp-homework

    13. **异步编程**:使用async和await关键字实现异步操作,避免阻塞主线程,提升用户体验。 14. **设计模式**:学习常见的设计模式,如工厂模式、单例模式、观察者模式等,将有助于编写更灵活、可维护的代码。 在"C...

    Xamarin Froms 调用相机拍照和图库选择图片

    在移动应用开发中,Xamarin.Forms 是一个强大的跨平台框架,允许开发者使用 C# 和 .NET 库创建原生 iOS、Android 和 UWP 应用。本教程将深入探讨如何在 Xamarin.Forms 应用中调用设备的相机进行拍照以及访问图库选择...

    cs9dotnet5一些简单示例比较容易看懂.zip

    .NET 5 引入了异步枚举器,这使得我们可以编写异步的 `yield return` 语句,创建异步可迭代的数据源,用于处理需要等待的异步操作,如文件读取或网络请求。 10. **改进的异步编程** 包括 `IAsyncDisposable` 接口...

    语法糖

    C#的异步编程模型使用`async`和`await`关键字,使得编写非阻塞的I/O密集型或网络操作变得简单。如: ```csharp async Task DownloadImageAsync(string url) { using var client = new HttpClient(); var ...

Global site tag (gtag.js) - Google Analytics