zoukankan      html  css  js  c++  java
  • C#中Await/Async中的线程ID疑惑

    今天写了个测试的代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Threading;
    
    namespace ConsoleApp2
    {
       public class AwaitAsyncClassNew
        {
            public async Task<int> Show() {
                Console.WriteLine($"aaaaaa.....{ Thread.CurrentThread.ManagedThreadId }");
                await Task.Run(
                        () => {
                            Console.WriteLine($"bbbbbbbbbbb.....{ Thread.CurrentThread.ManagedThreadId }");
                            Thread.Sleep(5000);
                            Console.WriteLine($"cccccccccccccc.....{ Thread.CurrentThread.ManagedThreadId }");
                        }
                    );
                Console.WriteLine($"dddddddddddddd.....{ Thread.CurrentThread.ManagedThreadId }");
    
                return 1;
            }
        }
    }

    运行结果如下:

     用反编译工具查看,代码经过编译后,变成如下的了:

    编译后,代码用 TaskAwaiter来实现了,我又写了一个例子,代码如下:

     public void TestTaskAwait() {
                Console.WriteLine($"This is Main Start.... {  Thread.CurrentThread.ManagedThreadId }");
    
                TaskAwaiter awaiter = Task.Run(() => {
                    Console.WriteLine($"This is Task Start.... {  Thread.CurrentThread.ManagedThreadId }");
    
                    Thread.Sleep(2000);
    
                    Console.WriteLine($"This is Task End.... {  Thread.CurrentThread.ManagedThreadId }");
                }).GetAwaiter();
                while (!awaiter.IsCompleted) {
                    Thread.Sleep(100);
                }
                awaiter.GetResult();
                Console.WriteLine($"This is Main End.... {  Thread.CurrentThread.ManagedThreadId }");
            }

    运行结果如下:

     此时猜测,是代码:

     <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this); 这行代码在作怪。(把当前运行的线程池改成子线程运行的线程池了)这个只是猜测

                awaiter.GetResult();
                Console.WriteLine($"dddddddddddddd.....{Thread.CurrentThread.ManagedThreadId}");
                result = 1;

    把这些代码都丢在新开启的子线程中在运行了。暂时还没找到依据。我的慢慢看,有谁知道的,请帮我解惑下。

  • 相关阅读:
    古代军队的官的从大到小的排序
    [转]DAO、RDO、ADO、OLE DB 、ODBC and JDB
    JSP页面之间参数传递中文出现乱码
    重置VS2008插件环境
    PB7中调用VC6的DLL
    Visual Studio统计有效代码行数
    php.ini 中文版
    IDEA Plugin JB* Components
    [转]你还在为怎么查看字节码指令而担忧吗?
    战地2, 2142解决Win10运行闪退问题
  • 原文地址:https://www.cnblogs.com/huaan011/p/14283520.html
Copyright © 2011-2022 走看看