async与await线程分配研究

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

namespace ATLearn
{
    /// <summary>
    /// Guid工厂
    /// </summary>
    static class GuidFactory
    {
        //private static ThreadLocal<string> _localGuid = new ThreadLocal<string>();
        private static AsyncLocal<string> _localGuid = new AsyncLocal<string>();
        public static string CurrentGuid
        {
            get
            {
                if (_localGuid.Value == null)
                {
                    _localGuid.Value = Guid.NewGuid().ToString();
                }
                return _localGuid.Value;
            }
        }
    }

    class APP
    {
        private Task<int> awaitFunction(int taskId)
        {
            return Task.Factory.StartNew((obj) =>
            {
                int itaskId = (int)obj;
                Console.WriteLine(string.Format("taskId: {0} Await! threadId: {1} Guid: {2}", taskId, Thread.CurrentThread.ManagedThreadId, GuidFactory.CurrentGuid));
                Thread.Sleep(2000);
                return itaskId;
            }, (object)taskId);
        } 

        private async void asyncFunction(int taskId)
        {
            Console.WriteLine(string.Format("taskId: {0} Start! threadId: {1} Guid: {2}", taskId, Thread.CurrentThread.ManagedThreadId, GuidFactory.CurrentGuid));
            int num = await awaitFunction(taskId);
            Console.WriteLine(string.Format("taskId:{0} End! threadId: {1} Guid: {2}", taskId, Thread.CurrentThread.ManagedThreadId, GuidFactory.CurrentGuid));
        }

        public APP()
        {
            for (int i = 1; i <= 2; ++i)
            {
                asyncFunction(i);
            }


            while (true)
            {
                Thread.Sleep(1000);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            APP App = new APP();
        }
    }
}

 

 

 

可见await会开新线程

 

 

async标志的函数为异步函数,异步函数内部,在进行await的时候会等待await后面一个线程运行结束

而第一次await的时候,异步函数就会跳过,执行主线程里异步函数之后的内容了

posted @ 2017-09-04 13:05  鸡毛巾  阅读(181)  评论(0编辑  收藏  举报