触发多个同步线程

时间:2011-05-12 10:25:12

标签: multithreading c#-4.0

我不确定这是否是一个愚蠢的问题,因为我对线程知之甚少,但是是否有可能同时触发多个同步线程,并等待所有线程完成然后再行动?如果是你怎么做的?

5 个答案:

答案 0 :(得分:3)

当然,最简单的方法是使用.NET 4.0的任务并行库(TPL)。

e.g。

Parallel.For(0, 10, x => 
// Do this in Parallel.
System.Diagnostics.Debug.WriteLine(x)
);

请参阅:http://msdn.microsoft.com/en-us/concurrency/bb964701

答案 1 :(得分:2)

  

是否可以同时触发多个同步线程,等待所有线程完成后才能完成?

“同步线程”是矛盾的,它们不存在。

当然,您可以启动多个线程并等待它们完成(Thread.Join(otherThread)

  

如果你是这样做的?

很少。始终使用尽可能少的线程。它们是昂贵的。

确保您了解ThreadPool和(Fx4)Tasks库,TPL

答案 2 :(得分:1)

您可以使用Parallel.Invoke 这将并行执行提供的操作,并在完成所有操作后返回。

答案 3 :(得分:0)

你不能同时做任何事情,更不用说火线了:)(你可以一个接一个地快速发射它们,虽然有可能线程会在之前启动最后一个被解雇了。)

至于在继续之前等待它们,你可以使用Join方法,它等待一个线程在继续之前结束。

答案 4 :(得分:0)

一般来说,你会使用如下所示的结构,

public class MultipleThreqadTest
{
    private readonly Thread[] threads;
    private readonly object locker;
    private int finishCounter;
    private readonly AutoResetEvent waitEvent;

    public MultipleThreqadTest()
    {
        threads=new Thread[10];
        for(int i=0;i<0;i++)
            threads[i]=new Thread(DoWork);
        finishCounter = threads.Length;
        waitEvent=new AutoResetEvent(false);

    }
    public void StartAll()
    {
        foreach (var thread in threads)
        {
            thread.Start();
        }
        //now wait for all worker threads to complete
        waitEvent.WaitOne();
    }


    private void DoWork()
    {
        //Do Some Actual work here, you may need to lock this in case you are workin on some shared resource
        //lock(locker)
        //{

        //}

        //Check if all worker thread complets
        if(Interlocked.Decrement(ref finishCounter)==0)
        {
            this.waitEvent.Set();
        }
    }

}