简体   繁体   中英

Single Child thread notifying Parent to indicate that it is finished so Parent can launch another child [C#]

I have a PARENT thread responsible for performing jobs, for each job it launches a CHILD thread to do the work - however it should never be allowed to launch more then one at a time (single child). For example in the case where there are 10 jobs to do it should do them one-after-another - therefore the PARENT needs to be know when each job has completed so it can launch the next pending one.

Typically I would just .Join() or a WaitHandle to accomplish this task - except that in this case I cannot block the Parent thread as it has other responsibilites that need to be performed while waiting for the child to complete ...

Allow me to illustrates:

class Parent
{

private Thread threadJob;

public Parent()
    {
    // this is where the main loop occurs
    while (bRun)
        {

        // This is where I need help ... how can I know that threadJob is not currently performing a task?
        // is there an event it can fire to let Parent know that it is done? A flag it can set?
        if (threadJob child is not currently running a job)
            {
            threadJob = new Thread(new ThreadStart(PerformWork));
            threadJob.IsBackground = true;
            threadJob.Start();
            }

        .. do other work ...
        .. keep doing other work ...

        }
    }
};

Any help or advice would be much appreciated. Thanks,

Another way of handling this is to keep the worker thread alive the whole time and have it read from a queue of pending jobs. This way, you only do one job at a time, in sequence, but you don't need to worry about synchronizing with the main thread. The output of the job can go into a queue of its own, which the main thread can check for empty and retrieve from if not.

edit

Looking at your example more closely, it doesn't appear that the work the thread does is different each time, so perhaps just have the thread loop instead of terminating.

如果您愿意按照问题所示进行有效轮询,则可以使用Thread.IsAlive

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