async与await线程分配研究

Posted 鸡毛巾

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的时候,异步函数就会跳过,执行主线程里异步函数之后的内容了

以上是关于async与await线程分配研究的主要内容,如果未能解决你的问题,请参考以下文章

async与await的疑问,await是导致线程同步吗

研究c#异步操作async await状态机的总结

将 async/await 与 Dispatcher.BeginInvoke() 一起使用

Swift新async/await并发中利用Task防止指定代码片段执行的数据竞争(Data Race)问题

Swift新async/await并发中利用Task防止指定代码片段执行的数据竞争(Data Race)问题

C# Async与Await的使用