Question

I have 2 decoupled classes, class A and class B, these two classes communicate with each other with event publication and event subscription using Mircosoft CAB framework :

public class ClassA
    {
        [EventPublication("ActionFired", PublicationScope.WorkItem)]
        public event EventHandler<EventArgs> ActionFired;

        public void MethodA()
        {
            // Some code 1
            DoAction1();
            // Some code 2
        }

        private void DoAction1()
        {
            if (ActionFired != null)
                ActionFired(this, EventArgs.Empty);
        }
    }

    public class ClassB
    {
        [EventSubscription("ActionFired")]
        public void OnActionFired(object sender, EventArgs e)
        {
            // Here some background work using BackgroundWorker
        }

        private void bagroudThread_DoWork(object sender, DoWorkEventArgs e)
        {
            // work 
        }

        private void bagroudThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
         {

         }
    }

Here in MethodA we call DoAction1(); that fire the event publication, the subscriber execute its handler in a background worker thread, the problem here that I want that 'some code 2' (that comes after calling DoAction1()) execute only after the background worker is completed, but here DoAction1() is executed asynchronously and 'some code 2' is executed before the classB background worker complete the work. How can I control the execution of MethodA?

Regards

Was it helpful?

Solution

You can use ManualResetEvent for this

public void MethodA()
{
    // Some code 1
    DoAction1();

    //call wait metod: eventWaitHandle.WaitOne

    // Some code 2
}


private void bagroudThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    //call set method:  eventWaitHandle.Set
}

OTHER TIPS

Using the signaling with the wait event handles solve the problem, I want just to mention the introduction of ManualResetEventSlim in the Microsoft .Net Framework 4.0 that is another version of ManualResetEvent and it is optimized for short waiting times with the ability to opt into spinning for a set number of iterations. It also has a more efficient managed implementation and allows a Wait to be canceled via a CancellationToken. See Signaling with Event Wait Handles for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top