简体   繁体   中英

Validate a raising of event

I try to validate a raising of event:

I have a Device which return me some message after I send it a command.

I have an event which is raise when I got new message on my serial port.

I recover this event and I want to do a validation of this raising before sending an other command to my Device.

Public Constructor()
{
 ModuleProtocole.MessageReceive += SendValidate;
}

SendValidate()
{
//maybe something to write here?
}

SendNewMessage()
{
 ModuleProtocole.SendMessage ("Version");
 // if SendValidate() is call because of event go to next line
 ModuleProtocole.SendMessage ("Value1");
}

If I understand the question, and to give the simplest possible answer.

private bool? _hasEventBeenRaised;

private void SendValidate()
{
   _hasEventBeenRaised = true;
}

private void SendNewMessage()
{
   if(_hasEventBeenRaised == false)
   {
      Console.WriteLine("No event received");
      return;
   }
   
   _hasEventBeenRaised = false;

   // send message
    
}

Note : This disregaurds any other issue, additionally if the event is raised on another thread, you will want to use lock to ensure there is no threading issues.

An overly cautious lock approach

private bool? _hasEventBeenRaised;
private object _sync = new object();

private void SendValidate()
{
   lock(_sync)
   {
      _hasEventBeenRaised = true;
   }
}

private void SendNewMessage()
{
    lock(_sync)
    {
       if(_hasEventBeenRaised == false)
       {
           Console.WriteLine("No event received");
           return;
       }
   
       _hasEventBeenRaised = false;

       // send message
    }
    
}

Why not just use the SendValidate function (which is a called when the device responds to the 1st message) to do the sending of the second message?

But ideally i'd do it with some signals, so basically i'd create a send message, which blocks - waits for a signal (initially should be free), then locks the signal (semaphore) and then sends the message. The message callback event then should free the signal.

https://docs.microsoft.com/en-us/dotnet/api/system.threading.semaphoreslim?view=netcore-3.1

var semaphore = new SemaphoreSlim(1, 1); // 1 available call, max. 1 concurrent calls

SendMessage()
{
  this.semaphore.WaitOne();
  // NOTE: add send message here
}

MessageReceived()
{
  this.semaphore.Release(1);
}

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