现在的位置: 首页 > 综合 > 正文

一个例子 理解 await

2014年02月09日 ⁄ 综合 ⁄ 共 823字 ⁄ 字号 评论关闭

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

//1: test: await before
//doo0
//1: Main:inoke test after
//doo1
//doo2
//doo3
//doo4
//3: test: await after

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            test();
            log("Main:inoke test after");
            Thread.Sleep(Timeout.Infinite);
        }

 
        static async void test()
        {
            log("test: await before");
            await doo();
            log("test: await after");
        }

        static async Task doo()
        {
             await Task.Run(() => {
                 for (int i = 0; i < 5; i++)
                 {
                    Console.WriteLine("doo" + i.ToString());
                     Thread.Sleep(1000);
                 }

             });
           
        }

        static void log(string msg)
        {
            Console.WriteLine("{0}: {1}", Thread.CurrentThread.ManagedThreadId, msg);
        }

    }
}

抱歉!评论已关闭.