Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SerialPort and Thread Safe

Status
Not open for further replies.

tzzdvd

Programmer
Aug 17, 2001
52
0
0
IT
Hi to all,
I am using c# since last week so I'am not so expert.
I have this problem: I have created a delegate function to handle the result of the data received and managed it with the method .InvokeRequire and .Invoke().
I show the code
Code:
delegate void SetCallBackRxMsg();

private void ReceivedSerialData(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
if (btnReception.Text == "Stop Reception")
{
    try
    {
        iRxIndex += controlSerialPort.Read(byRxMessage, iRxIndex, controlSerialPort.BytesToRead);
    }
    catch
    {
    }
    finally
    {
        if (iRxIndex > 1 && iRxIndex >= iLenMsg)
        {
            this.RxMessage();
        }
    }
}

private void RxMessage()
if (this.InvokeRequired)
{
    this.Invoke(new SetCallBackRxMsg(RxMessage), new object[] { });
}
else
{
    // message received
    // ...
}

Everything works very well till I close the form exactly while receiving datas.
The program blocks at line
Code:
this.Invoke(new SetCallBackRxMsg(RxMessage), new object[] { });
and wait for I don't know what.
I try to add this code on the Closing event of the form
Code:
private void myForm_FormClosing(object sender, FormClosingEventArgs e)
{
   if (controlSerialPort.IsOpen)
   {
      controlSerialPort.DiscardInBuffer();
      controlSerialPort.Close();
   }
}
but it is not helpfull.
Any ideas?
Thank's for all.
 
Try changing your call to Invoke to BeginInvoke. This will get the callback off the receiving thread and onto a thread from the default threadpool. This way you shouldn't block when closing the form (maybe).

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
It seems to function!!!
Thank you very much.

Davide
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top