简体   繁体   中英

class A waiting on ManualResetEvent from Thread in different class? [C#]

I have a parent thread (non-UI) which creates some child threads to do some jobs, these children are from a different class (sounds odd but the code sample will illustrate it) - at some point the parent must wait for certain tasks to be completed by the child thread - this does not mean the child is finished but only that it has reached a certain point and the parent can now continue processing ...

Obviously this is a sample to illustrate my situation ... life isn't this simple :) (sorry for the repost - was trying to add this as a comment to my previous one but the code never came out right)...

class A
{
private ManualResetEvent manualResetEvent;

public A()
    {
    manualResetEvent = new ManualResetEvent(false);
    B child = new B();

    if (manualResetEvent;.WaitOne(1000, false))
        {
        ... do the work I was waiting on ...
        }
    }
};


Class B
{
public B()
    {
    Thread childThread = new Thread(new ThreadStart(Manage));
    childThread.IsBackground = true;
    childThread.Name = "NamedPipe Manager";
    childThread.Start();

    private void Manage()
        {
        ... do some work ...
        ... call some functions ...

        // SIGNAL TO Class A THAT IT CAN CONTINUE //
        manualResetEvent.Set(); // this won't compile because obviously it has no clue what manualResetEvent is ... different class

        ... do more work ...
        ... call more functions ...
        }
    }
};

As you can see, this is a little different then before ... now we have two different classes (A & B) - the problem this raises is that B cannot see A's manualResetEvent and therefore cannot do .Set to notify it ...

Any one have any suggestions on how I can accomplish this task in a thread-safe manner? Any help would be much appreciated. Thanks,

Pass the ManualResetEvent reference along as a parameter to the B constructor?

You could also let the B class create it's own ManualResetEvent and expose it through a property, but if all B child threads have to share the same object, the first option would be preferable.

I'd say the event should be property of B rather of A, and A can wait on the child.Event.WaitOne() . If you must have the event on A, pass it to B's constructor so that B retain a reference to it.

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