C# How to make synchronous method waiting for events to fire?

10,360

Try use ManualResetEvent:

    var wait = new ManualResetEvent(false); 
    var handler = new EventHandler((o, e) => wait.Set()); 
    MyAsyncMethod(data, handler); // so it started and will fire handler soon 
    wait.WaitOne();
Share:
10,360
Harry
Author by

Harry

Co-founder of the CodeDog company. Author of the Woof Toolkit. Specializes in back-ends, APIs, IoT and general hacking. Tech enthusiast, a big fan of .NET, Windows, Linux and recently Rust on microcontrollers.

Updated on June 13, 2022

Comments

  • Harry
    Harry about 2 years

    I have custom browser class which is capable of firing a lot of events depending on browsed page state. Now I need to perform some operations on this web page using my browser, but they have to run sequentialy, each operation needs data from the previous one. The cleanest way to achieve this is to make a synchronous methods waiting for browser to do its job. I made it like this:

    public incomplete class MyClass {
        // (...) lots of stuff comes here, it's a web browser :)
        public bool MySyncMethod(object data) {
            bool success = false;
            bool wait = true;
            MyEventHandler = new EventHandler((o, e) => {
                data = MyEventProvidedData; // belive me, it's threre when it fired
                success = true; // let's assume it always succeed
                wait = false; // now we can move on to the rest of our long chain
            });
            // (...) here I have some more event handlers which can end my method...
            MyAsyncMethod(data); // so it started and will fire MyEventHandler soon
            while (wait) System.Threading.Thread.Sleep(100);
            return success;
       }
    }
    

    But something seems wrong here. If I used threads, I'd just place myThread.Join() instead of my while loop and it would wait for my thread to complete. Is it something similar to Thread.Join() which can be used with events fired by controls? Is there something to use instead of while loop? Is it a cleaner way to achieve my goal? The code above works in the real app, but I think it's not optimal.

    And there is a good reason I don't use threads here - all communication between threads and ActiveX control must be thread-safe, and this is not trivial to achieve. Yes, I tried :) This code was a hell to debug, so I decided to rewrite it.