none
How to use ManualResetEvent or AutoResetEvent to block an event in period of time ? RRS feed

  • General discussion

  • Hi

    in my code, i'm using ManualResetEvent to block my method until my event being rised. it works fine, but sometimes, my event is not rise for a long time, at the result, my method is still blocking! to avoid this problem, i should handle blocking my method with a period of time like TimeOut. with TimeOut, if my event does not rise in period of time, my method continue to implement other tasks.

    can anybody help me how to accomplish this task ?

    thanks in advance


    http://www.codeproject.com/KB/codegen/DatabaseHelper.aspx

    Monday, January 29, 2018 8:57 AM

All replies

  • All the Wait methods that you call to block on an event accept a timeout parameter. So if you want to block for a specific amount of time you can simply pass in a timeout. if the timeout expires then the method returns false. So your code can easily determine if the event was obtained or timed out. But the only reason you would probably want to go this route is if you wanted to cancel the wait (because it is taking too long) or to support cancellation requests (for example from the UI). Otherwise there is no benefit in periodically waking up the thread that is waiting.

    //For no real good reason, keep waiting for 5 seconds
    while (!myEvent.WaitOne(5000))
    {
       //Timed out, now what?
    };
    
    //Event has been set

    Without further information it is unclear what you mean by "implement other tasks" but it really sounds like maybe you shouldn't be waiting at all. The question boils down to what can be done in parallel and what needs to be serialized. Any work that needs to be serialized needs to be waited on until it completes (don't really need timeouts here other than for cancellation). For any work that can be done in parallel then use async calls to start the work. For each task that is returned put it into a list. Then, once all the work has started, then use a single WaitAll to wait for all the work to get done.

    //These need to happen in sequence
    DoWork1();
    DoWork2();
    
    //These can run in parallel
    var tasks = new List<Task>();
    tasks.Add(DoWorkAsync3());
    tasks.Add(DoWorkAsync4());
    tasks.Add(DoWorkAsync5());
    
    //Wait for all the parallel work to complete
    Task.WaitAll(tasks.ToArray());
    
    //All parallel work is done now
    


    Michael Taylor http://www.michaeltaylorp3.net

    Monday, January 29, 2018 3:46 PM
    Moderator