How to implement AutoResetEvent with Return Value ability?

51 Views Asked by At

I need to call WaitOne() at one place of code and call Set() at 2 another places.

It is related with chromiumwebbrowser and I'm making fulfilling of operations synchronously.

Place 1 - where browser operation is called. Place 2 - where browser status is changed to IsLoading = false. Place 3 - browsers error event handler, where I know about appearing errors while called opperation is performing. When I found error, I need to throw exception after Wait()

I need to send data about errors from Place 3 to Place 1

All this functionality I implemented in code bellow.

Place 1 receive information from Place 2 and 3 by private _message variable, but inside one class.

I just tryed to find temporary solution but I feel that people already faced with this case before and completed solutions already exists.

Can you:

  • give me advises about completed solutions for my perposes

  • give me advises for improving of my solution

    public class CustomAutoResetEvent { int? _waitTimeout = null;

      public CustomAutoResetEvent(int? waitTimeout = null)
      {
          _waitTimeout = waitTimeout;
      }
    
      // it is made for considiration of setting from many points
      // if event is setted from one point, another point doesn't change state
      bool _isSetted = false;
      AutoResetEvent _autoResetEvent = new AutoResetEvent(false);
    
      string _message { get; set; } = null;
      public void WaitOneThrow()  // Place 1
      {
          _isSetted = false;
          if (_waitTimeout==null)
              _autoResetEvent.WaitOne();
          else
              _autoResetEvent.WaitOne(_waitTimeout.Value);
    
          if (!string.IsNullOrEmpty(_message))
          {
              string msg = null;
              msg = _message;
              _message = null;
    
              //if (msg == "ERR_ABORTED")
              //    return;
    
              throw new Exception(msg);
          }
      }
    
      public void Set(string errMessage = null) // Place 2, 3
      {
          if (!_isSetted)
          {
               _message = errMessage;
              _autoResetEvent.Set();
              _autoResetEvent.Reset();
              _isSetted=true;
          }
      }
    

    }

0

There are 0 best solutions below