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.

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用.NET Framework 3.5实现异步编程的示例: ```csharp using System; using System.Threading; class Program { static void Main(string[] args) { Console.WriteLine("Main thread started."); // 使用委托和回调函数实现异步编程 Console.WriteLine("Using delegate and callback to implement asynchronous programming."); MyDelegate myDelegate = new MyDelegate(DoSomething); myDelegate.BeginInvoke(5000, new AsyncCallback(Callback), null); // 使用线程池实现异步编程 Console.WriteLine("Using thread pool to implement asynchronous programming."); ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomethingThreadPool), 3000); // 使用异步方法实现异步编程 Console.WriteLine("Using async method to implement asynchronous programming."); DoSomethingAsync(2000); Console.WriteLine("Main thread ended."); Console.ReadLine(); } // 定义委托和回调函数 public delegate void MyDelegate(int milliseconds); public static void DoSomething(int milliseconds) { Console.WriteLine("DoSomething started."); Thread.Sleep(milliseconds); Console.WriteLine("DoSomething completed."); } public static void Callback(IAsyncResult ar) { Console.WriteLine("Callback started."); MyDelegate myDelegate = (MyDelegate)ar.AsyncState; myDelegate.EndInvoke(ar); Console.WriteLine("Callback completed."); } // 使用线程池 public static void DoSomethingThreadPool(object state) { Console.WriteLine("DoSomethingThreadPool started."); int milliseconds = (int)state; Thread.Sleep(milliseconds); Console.WriteLine("DoSomethingThreadPool completed."); } // 使用异步方法 public static async void DoSomethingAsync(int milliseconds) { Console.WriteLine("DoSomethingAsync started."); await Task.Run(() => Thread.Sleep(milliseconds)); Console.WriteLine("DoSomethingAsync completed."); } } ``` 该示例使用了三种不同的方法来实现异步编程使用委托和回调函数、使用线程池、使用异步方法。在每种方法中,都使用Thread.Sleep方法模拟耗时操作。注意,在使用异步方法时,需要使用async和await关键字来标记异步方法和等待异步操作完成

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值