C#Threading - 产生多个线程,只有1或2个正在执行其他等待

时间:2010-08-19 06:38:41

标签: c# .net multithreading execution

我在下面有这个代码,我生成了几个线程,通常大约7个,然后加入它们等待一切完成:

            List<Thread> threads = new List<Thread>();
            Thread thread;
            foreach (int size in _parameterCombinations.Keys)
            {
                thread = new Thread(new ParameterizedThreadStart(CalculateResults));
                thread.Start(size);
                threads.Add(thread);
            }

            // wait for all threads to finish
            for (int index = 0; index < threads.Count; index++)
            {
                threads[index].Join();
            }

当我在大多数时间检查时,只有一个或两个线程同时运行,当我重新运行应用程序时,只执行一次或两次所有线程。

有没有办法强制所有线程开始执行?

非常感谢。

1 个答案:

答案 0 :(得分:0)

你的代码很好..我稍微改了一下,告诉你线程的执行不限于2个线程。 我会在计算过程中寻找问题..

class Program
{
    static void Main(string[] args)
    {
        List<Thread> threads = new List<Thread>();
        Thread thread;
        for (int i = 0; i < 7; i++)
        {
            thread = new Thread(new ParameterizedThreadStart(CalculateResults));
            thread.Start();
            threads.Add(thread);
        }

        // wait for all threads to finish
        for (int index = 0; index < threads.Count; index++)
        {
            threads[index].Join();
        }
    }

    static void CalculateResults(object obj)
    {
        Console.WriteLine("Thread number " + Thread.CurrentThread.ManagedThreadId + " is alive");
        Thread.Sleep(1000);
        Console.WriteLine("Thread number " + Thread.CurrentThread.ManagedThreadId + " is closing");
    }
}