代码改变世界

一个简单的异步处理程序

2014-01-21 13:03  Commander lang  阅读(913)  评论(0编辑  收藏  举报
1、新建一个wpf或winform程序 添加按钮startbtn 和asyncbtn
  后台代码如下:
using System;
using System.Windows.Forms;
///////////////////////////
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;

namespace simpleasync
{
    /// <summary>
    /// framework4.5 异步demo
    /// </summary>
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// !事件修饰符 async
        /// </summary>
        private async void startbtn_Click(object sender, EventArgs e)
        {
            Task<string> getWebPageTask = GetWebPageAsync("http://www.cnblogs.com");

            Debug.WriteLine("在 startButton_Click 任务执行前");
            string webText = await getWebPageTask;
            Debug.WriteLine("返回字符数: " + webText.Length.ToString()); 

        }

        private async Task<string> GetWebPageAsync(string url)
        {
            // 开始异步任务
            Task<string> getStringTask = (new HttpClient()).GetStringAsync(url);

            // 在等待任务的时候 会做下面两个事情
            // 1. 立即执行返回到调用方法, 返回一个不同的任务给任务被创建的前面声明的地方
            //    在这个方法里执行暂停. 
            // 2. 当在前面声明的任务创建完成后, 从GetStringAsync这个方法中产生等待语句, 
            //    并在这个方法中继续执行
            Debug.WriteLine("在 GetWebPageAsync 等待之前");
            string webText = await getStringTask;
            Debug.WriteLine("在 GetWebPageAsync 等待之后");

            return webText;
        }

        private async Task<string> DelayAsync()
        {
            await Task.Delay(100);

            // 取消以下注释 证明异常处理

            //throw new OperationCanceledException("canceled"); 
            //throw new Exception("Something happened."); 
            return "Done";
        }

        private async void asyncbtn_Click(object sender, EventArgs e)
        {
            Task<string> theTask = DelayAsync();

            try
            {
                string result = await theTask;
                Debug.WriteLine("Result: " + result);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception Message: " + ex.Message);
            }
            Debug.WriteLine("Task IsCanceled: " + theTask.IsCanceled);
            Debug.WriteLine("Task IsFaulted:  " + theTask.IsFaulted);
            if (theTask.Exception != null)
            {
                Debug.WriteLine("Task Exception Message: "
                    + theTask.Exception.Message);
                Debug.WriteLine("Task Inner Exception Message: "
                    + theTask.Exception.InnerException.Message);
            }
        }


    }


}

 2、程序运行结果:

3、到底在异步的过程中发生了什么?

 这有个类似的程序:

 

原文链接:

http://blogs.msdn.com/b/csharpfaq/archive/2012/06/26/understanding-a-simple-async-program.aspx

http://msdn.microsoft.com/en-us/library/vstudio/hh191443(v=vs.110).aspx