• C# 异步编程,有时候我们需要拿到异步任务计算体完成计算的数据,请使用task.AsyncState去获取。


    直接上代码,运行下就知道怎么回事呢。

    
    using System;
    using System.Threading;
    using System.Threading.Tasks;
    
    
    class CustomData
    {
        public long CreationTime;
        public int Name;
        public int ThreadNum;
    }
    
    public class AsyncState
    {
        public static void Main()
        {
            Task[] taskArray = new Task[10];
            for (int i = 0; i < taskArray.Length; i++)
            {
                taskArray[i] = Task.Factory.StartNew((Object obj) =>
                {
                    CustomData data = obj as CustomData;
                    if (data == null) return;
    
                    data.ThreadNum = Thread.CurrentThread.ManagedThreadId;
                },
                new CustomData() { Name = i, CreationTime = DateTime.Now.Ticks });
            }
            Task.WaitAll(taskArray);
            foreach (var task in taskArray)
            {
                var data = task.AsyncState as CustomData;
                if (data != null)
                    Console.WriteLine("Task #{0} created at {1}, ran on thread #{2}.",
                                      data.Name, data.CreationTime, data.ThreadNum);
            }
        }
    }
    // The example displays output like the following:
    //     Task #0 created at 635116412924597583, ran on thread #3.
    //     Task #1 created at 635116412924607584, ran on thread #4.
    //     Task #2 created at 635116412924607584, ran on thread #4.
    //     Task #3 created at 635116412924607584, ran on thread #4.
    //     Task #4 created at 635116412924607584, ran on thread #3.
    //     Task #5 created at 635116412924607584, ran on thread #3.
    //     Task #6 created at 635116412924607584, ran on thread #4.
    //     Task #7 created at 635116412924607584, ran on thread #4.
    //     Task #8 created at 635116412924607584, ran on thread #3.
    //     Task #9 created at 635116412924607584, ran on thread #4.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    其中task.AsyncState就是你任务初始化传入的对象。

  • 相关阅读:
    uniapp的生命周期
    用嘉立创查找元件的原理图
    CleanMyMac X靠谱苹果电脑杀毒软件
    C++STL学习笔记-map的属性(大小以及是否存在)
    xss-labs/level15
    Java--Spring和MyBatis集成
    ELK日志系统
    ssm小微企业人事管理系统的设计与实现毕业设计源码261630
    k8s:endpoint
    HOC示例
  • 原文地址:https://blog.csdn.net/csdn2990/article/details/134337699