2011-05-12 40 views
1

我不确定这是否是一个愚蠢的问题,因为我对线程了解不多,但能否同时触发多个同步线程,并等待所有线程完成演戏之前?如果这是你怎么做的?关闭多个同步线程

回答

1

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

+0

这听起来像最简单的方法 – jcvandan 2011-05-12 10:47:10

+0

@dormisher:它是:-) – 2011-05-12 10:47:41

+0

干杯人 - 将执行时间从703秒减少到200毫秒! – jcvandan 2011-05-12 10:55:22

0

你不能真的做什么东西在同一时间,更不用说发射线程:)(你可以一个接一个地快速发射它们,虽然有可能一个线程在最后一个之前开始解雇)。

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

2

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

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

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

如果是你怎么做呢?

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

确保你知道的线程池和(FX4)的任务库,TPL

+0

谢谢,我不要太费心有关性能,这是一个难得的ocurrence和我做的唯一reaosn是因为我必须立即多次调用Web服务 – jcvandan 2011-05-12 10:43:58

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(); 
     } 
    } 

}