C#等待其他线程 [英] C# wait for other threads

查看:233
本文介绍了C#等待其他线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有找到能够适应我的问题的答案.

I haven't found an answer I was able to adapt to my problem.

这是这种情况: 我需要测试12个网络摄像机的功能,所有这些工作均相同. 因此,我正在启动12个线程,并连接到摄像机.

So this is the situation: I need to test functionality of 12 network cameras, all doing the same work. So, I am starting 12 threads, connecting to the cameras.

每个线程正在发送一个激活命令,然后等待10秒以获取响应,这是预期不到的.

Each thread is sending an activation command, then waiting 10 seconds for a response, which is not expected to come.

这10秒钟之后,线程应进入等待状态,并通知主线程有关此信息.

After these 10 seconds, the threads should go into a waiting state and inform the main thread about this.

一旦所有12个线程都处于等待状态,将通过串行连接发送命令,并且线程应继续其工作.现在他们应该会得到答案.

Once all 12 threads are in the waiting state, a command is sent over a serial connection and the threads should continue their work. Now they should receive an answer.

到目前为止,我已经启动了12个线程,但是我不知道如何在这一点上使它们同步.

So far, I got the 12 threads started, but I don't know how to get them synchronized at this one point.

有帮助吗?

到目前为止的代码:

Dictionary<String, Thread> tl = new Dictionary<String, Thread>();
Thread t;
foreach (String ip in this.ips) {
    t = new Thread(new ParameterizedThreadStart(camWorker));
    tl.Add(ip, t);
    tl[ip].Start();
}

但是,如果需要的话,可以重建它来为每个线程创建单独的类实例.

But it could be rebuilt to create individual class instances for each thread, if that is required.

推荐答案

您可以使用重置事件.为每个线程创建一个重置事件,最后,等待所有12个重置事件完成.

You could use reset events. Create a reset event for every thread and at the end, wait on all 12 reset events to finish.

示例:

var resetEvents = new List<AutoResetEvent>();
for (int i = 0; i < 12; i++)
{
   var re = new AutoResetEvent(false);
   resetEvents.Add(re);

   ThreadPool.QueueUserWorkItem(w =>
   {
       var threadReset = w as AutoResetEvent;
       var random = new Random();
       try
       {
          // do something.
          Thread.Sleep(random.Next(100, 2000));
       }
       catch (Exception ex)
       {
          // make sure you catch exceptions and release the lock.
          // otherwise you will get into deadlocks
       }

       // when ready:
       Console.WriteLine("Done thread " + Thread.CurrentThread.ManagedThreadId);
       threadReset.Set();
    }, re);
}

// this bit will wait for all 12 threads to set
foreach (AutoResetEvent resetEvent in resetEvents)
{
   resetEvent.WaitOne();
}

// At this point, all 12 of your threads have signaled that they're ready.

这篇关于C#等待其他线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆