简体   繁体   中英

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. So, I am starting 12 threads, connecting to the cameras.

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

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

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.

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

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.

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. 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

It sounds like a good case for Tasks. Essentially you can wait on 12 tasks, each checking the status of one camera. 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 . Task.WaitAll blocks the current thread until all tasks have run to completion.

It's not clear what you'd be calling this code from, but if appropriate, you could use the async features of C# too.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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