SerialPort component problem while ReadLine()

K

korayk

i am trying to use this SerialPort component of .NET 2.0 framework in a
very simple windows application and i am getting following exceptions:

A first chance exception of type 'System.ArgumentOutOfRangeException'
occurred in System.dll
A first chance exception of type 'System.IO.IOException' occurred in
System.dll

with the exception message:

Message="The I/O operation has been aborted because of either a thread
exit or an application request."


in the code, i use an eventhandler to receive incoming data as follows:

private void Form1_Load(object sender, EventArgs e)
{
serialPort1.DataReceived += new
SerialDataReceivedEventHandler(serialPort_DataReceived);
}

private void serialPort_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
textBoxReceived.Text = serialPort1.ReadLine();
}


as i have said, it is very simple and fundemantal. although i checked
every property of my comm port etc., i could not find the reason.

would be grateful for any kind of help...
 
D

Dick Grier

You cannot assign data directly to a textbox in the DataReceived event. You
assign it to a string buffer, then call a delegate to assign that buffer to
the textbox. The DataReceived event is generated in the thread context of
the SerialPort1 object, not the STAThread context of the UI. Call the
delegate using this.Invoke or this.BeginInvoke. You can download a VB
example from my web site -- the C# syntax will be (almost) the same.

--
Richard Grier, MVP
Hard & Software
Author of Visual Basic Programmer's Guide to Serial Communications, Fourth
Edition,
ISBN 1-890422-28-2 (391 pages, includes CD-ROM). July 2004, Revised March
2006.
See www.hardandsoftware.net for details and contact information.
 
K

korayk

thanks for your reply Richard, but your suggestion didn't work.

even if i don't assign the read data directly to a textbox, but to a
string buffer (as you've said), i get the same exception just at the
following line:
string buffer = serialPort1.ReadLine();

(error message is: "The I/O operation has been aborted because of
either a thread exit or an application request.")

i should also note that the codepieces i have written in my first post
were taken exactly from an MSDN sample application.

any further suggestions?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top