簡體   English   中英

在循環中使用 C# 中的 ThreadPool 並等待所有線程完成

[英]Use ThreadPool in C# within a loop and wait for all threads to finish

我在 C# 中有一個如下所示的簡單代碼:

using System;
using System.Threading;
using System.Diagnostics;


namespace ThreadPooling
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Enter the number of calculations to be made:");
            int calculations= Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Thread Pool Execution");

            for (int i = 1; i <= calculations; i++)
            {
                Console.WriteLine("Staring process " + i + "...");
                ThreadPool.QueueUserWorkItem(new WaitCallback(Process(i)));
            }

            Console.WriteLine("All calculations done.");
            Console.WriteLine("\nPress any key to exit the program...");
            Console.ReadKey();

        }

        static void Process(object callback, int name)
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine(i + " is the current number in " +  name);
            }
        }


    }
}

我希望main能夠使用線程池和參數調用Process 然后我希望程序在告訴用戶它完成之前等待所有線程完成。 我該怎么做? 似乎我無法在 Process 中放置參數,我得到: Error CS7036 There is no argument given that corresponds to the required formal parameter 'name' of 'Program.Process(object, int)'

而且我不清楚如何告訴 C# 在告訴用戶它完成之前等待循環中的所有進程完成。

.NET 已經快 20 年了,里面有幾代改進的 API。

這對於較新的任務並行庫方法來說是微不足道的。 例如

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ThreadPooling
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Enter the number of calculations to be made:");
            int calculations = Convert.ToInt32(Console.ReadLine());

            var tasks = new List<Task>();
            for (int i = 1; i <= calculations; i++)
            {
                int processNum = i;
                Console.WriteLine("Staring process " + processNum + "...");
                var task = Task.Run(() => Process(processNum));
                tasks.Add(task);
            }

            Task.WaitAll(tasks.ToArray());
            Console.WriteLine("All calculations done.");
            Console.WriteLine("\nPress any key to exit the program...");
            Console.ReadKey();

        }

        static void Process(int name)
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine(i + " is the current number in " + name);
            }
        }


    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM