Big problem with syncronize serialport

Hi all, I have a problem, how can I synchronize two methods?
Example:

In the main program I have a timer that elapsed any 50ms generates an event, in this event send a stream byte in the serial!
And I have 2 button, 1 button send another code in the serial and the 2 button send another code in the serial:


        private void timer1_Tick(object sender, EventArgs e) //50ms
        {
                        _serial.send(comand.get);
        }
        private void button1_Click_1(object sender, EventArgs e)
        {
            _serial.send(comando.start);
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            _serial.send(comando.stop);
        }

In the code of class serialport, the method send, send in the serial the relative command


class serial
{
        public void send(object command1)
        {
            switch (command1)
            {
                case comando.start:
                    buffertx[0] = (byte)'s';
                    _SerialPort.Write(buffertx, 0, 1);
                    break;
                case comando.stop:
                    buffertx[0] = (byte)'S';
                    _SerialPort.Write(buffertx, 0, 1);
                    break;
                case comando.get:
                    buffertx[0] = (byte)'U';
                    _SerialPort.Write(buffertx, 0, 1);
                    break;
        }
}

Now work, but the problem is the serial receive:
I want to synchronize the method send with the method event serial data receive :
when I send a command, I have to wait for a response before sending another command


class serial
{
        public void send(object command1)
        {
            lock(this)
            {
                 switch (command1)
                 {
                     case comando.start:
                         buffertx[0] = (byte)'s';
                         _SerialPort.Write(buffertx, 0, 1);
                         break;
                     case comando.stop:
                         buffertx[0] = (byte)'S';
                         _SerialPort.Write(buffertx, 0, 1);
                         break;
                     case comando.get:
                         buffertx[0] = (byte)'U';
                         _SerialPort.Write(buffertx, 0, 1);
                         break;
                  }

             // at this point you should wait for a response
             // You can wait on an AutoResetEvent  which is set in the data receive event
             // to notify the waiting thread that the response is ready
             theEvent.WaitOne(...

          } //end lock
     }
}

You might need locking in other methods also…

Thanks you very mutch!!! :slight_smile: