关于多线程:使用C#中的输入列表进行多线程处理

Multi threading with a list of input in C#

我对多线程完全陌生。我正在努力做一个简单的测试我有一张从1到100的数字表。我要多线程处理的函数只是一个将数字乘以5再乘以console.writeline的函数。

类程序{public static list data=new list();公共静态void main(string[]参数){新程序().run();foreach(数据中的int d){console.writeline(d);}

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
    }
    int multiply (int a){
        return 5 * a;
    }
    void run()
    {
        int threadCount = 5;
        Task[] workers = new Task[threadCount];

        Task.Factory.StartNew(consumer);

        for (int i = 0; i < threadCount; ++i)
        {
            int workerId = i;
            Task task = new Task(() => worker(workerId));
            workers[i] = task;
            task.Start();
        }

        for (int i = 0; i < 100; ++i)
        {
            Console.WriteLine("Queueing work item {0}", i);
            inputQueue.Add(i);
            Thread.Sleep(50);
        }

        Console.WriteLine("Stopping adding.");
        inputQueue.CompleteAdding();
        Task.WaitAll(workers);
        outputQueue.CompleteAdding();
        Console.WriteLine("Done.");

        Console.ReadLine();
    }

    void worker(int workerId)
    {
        Console.WriteLine("Worker {0} is starting.", workerId);

        foreach (int workItem in inputQueue)
        {
            int b= multiply(workItem);
            data.Add(b);
            Console.WriteLine("Worker {0} is processing item {1}." ,workerId,b);
            Thread.Sleep(100);          // Simulate work.
            outputQueue.Add(workItem);  // Output completed item.
        }

        Console.WriteLine("Worker {0} is stopping.", workerId);
    }

    void consumer()
    {
        Console.WriteLine("Consumer is starting.");

        foreach (var workItem in outputQueue.GetConsumingEnumerable())
        {
            Console.WriteLine("Consumer is using item {0}", workItem);
            Thread.Sleep(25);
        }

        Console.WriteLine("Consumer is finished.");
    }

    BlockingCollection<int> inputQueue = new BlockingCollection<int>();
    BlockingCollection<int> outputQueue = new BlockingCollection<int>();
}


这就是你要问的吗?

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
using System;
using System.Collections.Generic;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        List<int> list = new List<int>();

        for (int i = 0; i <= 100; i++) { list.Add(i); }

        foreach (int value in list)
        {
            Thread thread = new Thread(() => PrintNumberTimesFive(value));
            thread.Start();
        }

        Console.ReadLine();
    }

    static void PrintNumberTimesFive(int number)
    {
        Console.WriteLine(number * 5);
    }
}