task code

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
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
 
public class Example
{
    public static void Main()
    {
        var qTasks = new List<Task<string>>();
        var paralist = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        foreach (var para in paralist)
        {
            //StartNew 只接受输入参数是object类型的Func
            var fun = new Func<object, string>(
                (pa) =>
                {
                    //pa 是Func的定义参数
                    Console.WriteLine("para is {0}", pa);
                    //Thread.Sleep(new Random().Next(500, 3000));
                    int ipa = Convert.ToInt32(pa);
                    int result = ipa * 5;
                    return result.ToString();
                }
                );
 
            var task = Task.Factory.StartNew(fun, para); //para是传入参数
            qTasks.Add(task);
            Console.WriteLine(" task id is {0}", task.Id);
        }
 
        Task.WaitAll(qTasks.ToArray());  //等待所有线程执行完毕
 
        //收集所有task返回的数据
        foreach (var task in qTasks)
        {
            if (task.Result != null)
            {
                Console.WriteLine("task id : {0} , result : {1} ", task.Id, task.Result);
            }
        }
 
        Console.ReadKey();
    }
}

  

有时候会需要用到ManualResetEvent来等待其他线程是否执行完毕,用法如下:

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
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
 
public class Example
{
    static ManualResetEvent manualEvent = new ManualResetEvent(false);
 
    public static void Main()
    {
        manualEvent.Reset(); //等同于将initialState设置为false
 
        Console.WriteLine("In main ..");
        LongTimeFunc();
 
        manualEvent.WaitOne(10000);
 
        Console.WriteLine("wait thread finish...");
 
        Console.ReadKey();
    }
 
 
    private static void LongTimeFunc()
    {
        //Thread 多数时候可以使用Task代替,此刻thread设置为STA,所以这么用
        Thread thread = new Thread(new ParameterizedThreadStart(ExecuteFunc));
        thread.SetApartmentState(ApartmentState.STA);
        thread.IsBackground = true;
        thread.Start("real parameters");    //ExecuteFunc 函数从此处传入参数
    }
 
    private static void ExecuteFunc(object obj)
    {
        //long time operation
        Thread.Sleep(2000);
        Console.WriteLine(obj.ToString());
        manualEvent.Set();
    }
}

  

 

posted @   三叶草╮  阅读(429)  评论(0编辑  收藏  举报
编辑推荐:
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
阅读排行:
· 对象命名为何需要避免'-er'和'-or'后缀
· JDK 24 发布,新特性解读!
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· SQL Server如何跟踪自动统计信息更新?
点击右上角即可分享
微信分享提示