请帮忙。创建线程并等到完成

时间:2010-04-22 04:32:54

标签: c# .net multithreading

  

可能重复:
  C# Spawn Multiple Threads for work then wait until all finished

我想用两个线程调用两个方法调用。然后我希望他们等到方法执行完成后再继续。我的示例解决方案如下所示。

    public static void Main()
    {   
        Console.WriteLine("Main thread starting.");
        String[] strThreads = new String[] { "one", "two" };

        String ctemp = string.Empty;
        foreach (String c in strThreads)
        {
            ctemp = c;
            Thread thread = new Thread(delegate() { MethodCall(ctemp); });
            thread.Start();
            thread.Join();
        }

        Console.WriteLine("Main thread ending.");
        Console.Read();
    }


    public static void MethodCalls(string number)
    {
        Console.WriteLine("Method call " + number);
    }

这可以胜任吗?还是有另一种更好的方法来做同样的事情吗?

5 个答案:

答案 0 :(得分:3)

我会考虑通过ThreadPool.QueueUserWorkItem运行您的方法,然后使用WaitHandle.WaitAll等待所有这些方法完成。

答案 1 :(得分:1)

这一系列陈述......:

        Thread thread = new Thread(delegate() { MethodCall(ctemp); });
        thread.Start();
        thread.Join();

等同于直接调用方法 - 因为你在等待新线程在启动后立即完成,所以线程没有任何好处!您需要首先启动循环中的所有线程(将它们放在数组列表或类似的容器中),然后将它们连接到一个单独的循环中,以获得并发执行方法。

答案 2 :(得分:1)

你正在做什么,创造一个线程然后等待一个接一个地完成。在任何时候,您最多有两个线程运行:main和一个开始运行。

你想要的是启动所有线程,然后等待所有线程完成:

public static void Main()
{   
    Console.WriteLine("Main thread starting.");
    String[] strThreads = new String[] { "one", "two" };

    int threadCount = strThreads.Length;
    AutoResetEvent eventdone = new AutoResetEvent(false);

    String ctemp = string.Empty;
    foreach (String c in strThreads)
    {
        ctemp = c;
        Thread thread = new Thread(delegate() { 
            try
            {
               MethodCall(ctemp); 
            }
            finally 
            {
               if (0 == Interlocked.Decrement(ref threadCount) 
               {
                  eventDone.Set();
               }
            }
        });
        thread.Start();
    }

    eventDone.WaitOne();

    Console.WriteLine("Main thread ending.");
    Console.Read();
}


public static void MethodCalls(string number)
{
    Console.WriteLine("Method call " + number);
}

答案 3 :(得分:0)

如果你打算让你的两个线程一个接一个地执行,那么是的,上面的代码就足够了(虽然我的C#语法知识有点模糊,所以我不能说如果上面的话很好地编译或不编译),但如果你想要有序的同步执行,为什么要使用线程?

如果你需要的是两个方法调用并行执行,你需要从for循环中取出thread.Join();(你需要挂起线程对象,可能在一个数组。)

答案 4 :(得分:0)

看看BackgroundWorker Component;我相信它适用于Windows Forms,WPF和Silverlight,基本上涉及到UI