Threading in System.IO.Ports

A

Alex Moskalyuk

I downloaded the Visual C# express, which includes the .NET Framework 2.0.

The following exception is generated:

{"Illegal cross-thread operation: Control 'textBox1' accessed from a
thread other than the thread it was created on."}

on the following code:

namespace WindowsApplication1
{
partial class Form1 : Form
{
//private string buffer;
public Form1()
{
InitializeComponent();
this.serialPort1.Open();
if (this.serialPort1.IsOpen)
this.textBox1.AppendText("Port opened successfully");
}

private void serialPort1_ReceivedEvent(object sender,
System.IO.Ports.SerialReceivedEventArgs e)
{
this.textBox1.AppendText(this.serialPort1.ReadExisting()); ;
}
}
}

Both SerialPort and TextBox object are dragged from the Toolbox in
Visual C# 2005 Express Beta.

Alex
 
J

John Wood

The ReceivedEvent is probably raised from another thread. The UI controls
are not thread safe. Previous versions of .Net would allow these
thread-unsafe to be made, but they will cause weird things to happen (often
resulting in the application just disappearing) eventually. .Net 2 detects
these bad cross-thread calls, and raises an exception.

When in another thread, you should invoke all UI control methods using
BeginInvoke and EndInvoke rather than directly.

See this for more info:
http://msdn.microsoft.com/library/e...msControlClassBeginInvokeTopic.asp?frame=true
 

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