简体   繁体   English

C#等待其他线程

[英]C# wait for other threads

I haven't found an answer I was able to adapt to my problem. 我没有找到能够适应我的问题的答案。

So this is the situation: I need to test functionality of 12 network cameras, all doing the same work. 这就是这种情况:我需要测试12个网络摄像机的功能,所有这些工作都相同。 So, I am starting 12 threads, connecting to the cameras. 因此,我正在启动12个线程,并连接到摄像机。

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. 在这10秒钟之后,线程应进入等待状态并通知主线程有关此信息。

Once all 12 threads are in the waiting state, a command is sent over a serial connection and the threads should continue their work. 一旦所有12个线程都处于等待状态,就通过串行连接发送命令,并且线程应继续其工作。 Now they should receive an answer. 现在他们应该会得到答案。

So far, I got the 12 threads started, but I don't know how to get them synchronized at this one point. 到目前为止,我已经启动了12个线程,但是我不知道如何在这一点上使它们同步。

Any help? 有什么帮助吗?

Code so far: 到目前为止的代码:

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. 但是,如果需要,可以将其重建以为每个线程创建单独的类实例。

You could use reset events. 您可以使用重置事件。 Create a reset event for every thread and at the end, wait on all 12 reset events to finish. 为每个线程创建一个重置事件,最后,等待所有12个重置事件完成。

Example: 例:

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.
bool[] timeout = new bool[12];
bool waitForSignal = true;
oneof12()
{
    while(true)
    {
        if(receivedatabeforetimeout())
        {


        }
        else
            timeout[0] = true;
        while(waitForSignal)
            Thread.Sleep(500);
    }
}

watcherThread()
{
    bool allTimeout = true;
    for(int a = 0; a<12;a++)
        if(!timeout[0])
            allTimeout = false;

    if(allTimeout)
    {
        for(int a = 0; a<12;a++)
            timeout[a] = false;
        waitForSignal = false;
    }
Thread.Sleep(200);
}

Will something like this work in your case? 这样的事情适合您的情况吗? Each of the 12 threads sets a index in the bool array to true if it timed out. 如果超时,则12个线程中的每个线程都会将bool数组中的索引设置为true。 The watcher thread checks the bool array if all 12 have timed out and if they have it sets the waitForSignal flag to true which causes the 12 threads to go out of the while loop and again wait for the data 监视线程检查bool数组是否全部12个都超时,并且是否将其设置为true,从而将waitForSignal标志设置为true,这将导致12个线程退出while循环并再次等待数据

It sounds like a good case for Tasks. 这听起来像是Tasks的好案例。 Essentially you can wait on 12 tasks, each checking the status of one camera. 本质上,您可以等待12个任务,每个任务都检查一台摄像机的状态。 The advantage here being you don't have to manage your independent threads. 这样做的好处是您不必管理独立线程。

using System.Linq;
using System.Threading.Tasks;

...

var Tasks = this.ips.Select(ip => Task.Run(() => Check(ip))).ToArray();

Task.WaitAll(Tasks);

//inspect Task.Result to display status and perform further work

Note that your Check method can return a result, which is then accessible via Task.Result . 请注意,您的Check方法可以返回结果,然后可以通过Task.Result访问。 Task.WaitAll blocks the current thread until all tasks have run to completion. Task.WaitAll阻止当前线程,直到所有任务运行完毕。

It's not clear what you'd be calling this code from, but if appropriate, you could use the async features of C# too. 目前尚不清楚您将从何处调用此代码,但是如果合适,您也可以使用C#的异步功能。

I'd suggest using Tasks for this. 我建议为此使用任务。

List<Task> tasks = new List<Task>();

for (int i=0; i<10; i++)
{
    tasks.Add(Task.Factory.StartNew(() => DoSomething());
}

Task.WaitAll(tasks);

This will have all tasks running in parallel in the background and will wait until they all complete to proceed. 这将使所有任务在后台并行运行,并将等待所有任务完成才能继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM