简体   繁体   English

单个子线程通知父级以指示其已完成,以便父级可以启动另一个子级[C#]

[英]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). 我有一个PARENT线程负责执行作业,每执行一个作业,它都会启动一个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. 例如,在有10个工作要做的情况下,应一个接一个地做-因此,需要知道每个作业何时完成,以便可以启动下一个待处理的工作。

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 ... 通常,我只需要.Join()或WaitHandle即可完成此任务-除非在这种情况下,我无法阻止Parent线程,因为它在等待孩子完成操作时还需要执行其他职责...

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

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

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