如何使所有线程等待一个线程

本文关键字:线程 一个 等待 何使所 | 更新日期: 2023-09-27 18:25:05

我需要启动一个线程,该线程向200个不同的线程发送一个字符串(url),然后它们就会启动。然后第一个线程停止。当这个url返回404错误时,所有线程都必须停止,第一个线程需要启动。我该如何组织它?谢谢

对不起我的英语。我希望你能理解我)

如何启动线程:

Thread[] thr;
int good_delete;
static object locker = new object();
private void button1_Click(object sender, EventArgs e)
{
    button1.Enabled = false;
    button2.Enabled = true;
    decimal value = numericUpDown1.Value;
    int i = 0;
    int j = (int)(value);
    thr = new Thread[j];
    for (; i < j; i++)
    {
        thr[i] = new Thread(new ThreadStart(go));
        thr[i].IsBackground = true;
        thr[i].Start();
    }
}

如何使所有线程等待一个线程

您应该使用WaitHandle.WaitAll方法。有关更多信息,请参阅此参考资料。

编辑您的代码可能看起来像:

int j = (int)(value);
thr = new Thread[j];
ManualResetEvent[] manualEvents = new ManualResetEvent[j];
for (int i = 0; i < j; i++)
{
    manualEvents[i] = new ManualResetEvent(false);
    ThreadPool.QueueUserWorkItem(new WaitCallback(go), manualEvents[i]);
}
WaitHandle.WaitAll(manualEvents);

之后,您应该在go方法中设置事件:

private void go(object state)
{
    //put your code here
    ((ManualResetEvent)state).Set();
}

还要注意,传递给WaitAll方法的WaitHandle对象的最大数量为64,因此您必须手动拆分源。

祝你好运!

任何实现目标的方法都应该使用线程对象的Join方法

  for (; i < j; i++)
  {
    thr[i] = new Thread(new ThreadStart(go));
    thr[i].IsBackground = true;
    thr[i].Start();
  }
  for (; i < j; i++)
  {
    thr[i].Join();
  }