C# async await 學習筆記1

因爲個人開發工具爲vs.net 2010(.net 4.0),需先作如下兩步才能進行:異步

1.下載並安裝Async CTP (http://www.microsoft.com/en-us/download/details.aspx?id=9983)async

2.添加AsyncCtpLibrary.dll的引用,我用的是win7在(C:\Users\Administrator\Documents\Microsoft Visual Studio Async CTP\Samples)工具

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static Task<string> LongTimeTask()
        {          
            Console.WriteLine("LongTimeTask開始:" + DateTime.Now.ToString() + "  ThreadId:" + Thread.CurrentThread.ManagedThreadId);

            Task<string> task = new Task<string>(() => { Thread.Sleep(5000); return "這是任務返回值"; });
            task.Start();

            Console.WriteLine("LongTimeTask結束:" + DateTime.Now.ToString());

            return task;
        }

        static async void AsyncCall()
        {
            Console.WriteLine("AsyncCall開始:" + DateTime.Now.ToString() + "  ThreadId:" + Thread.CurrentThread.ManagedThreadId);

            string result = await LongTimeTask(); //await調用的方法須要返回Task或Task<T>,且調用await所在的方法要有async關鍵字
            Console.WriteLine("AsyncCall:" + result);

            Console.WriteLine("AsyncCall結束:" + DateTime.Now.ToString());
        }   

        static void Main(string[] args)
        {
            Console.WriteLine("Main開始:" + DateTime.Now.ToString() + "  ThreadId:" +Thread.CurrentThread.ManagedThreadId);
            AsyncCall();   
            Console.WriteLine("Main結束:" + DateTime.Now.ToString());      
            Console.ReadLine();
        }
    }
}

 

運行結果:開發工具

 不知你們注意到,裏面的ThreadId是一致的。spa

 

 須要注意的是,並非加了async,就是異步了(而是得裏面有調用await方法),例如,下面實際上是同步執行的.net

 static async void SyncCall()
        {
            Thread.Sleep(5000);
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Main開始:" + DateTime.Now.ToString());
            // AsyncCall();
            SyncCall();
            Console.WriteLine("Main結束:" + DateTime.Now.ToString());

            Console.ReadLine();
        }

 

 

相關文章
相關標籤/搜索