Possible Duplicate:
Getting Cross-thread operation not valid
Cross-thread operation not valid
I am trying to listen to COM port so that I create new handler for SerialPort.DataReceived event. The logic is simple - I write something to TextBox1, press Button1 and my text should show it self in Label1. But my application don t want to run, becouse it throws Cross thread operation not valid error. I did some searching and found Invoke object - how can I use it in my example? Why do I need to include Invoke logic?
namespace WindowsApplication1
{
public partial class Form1 : Form
{
SerialPort sp = new SerialPort();
public Form1()
{
InitializeComponent();
sp.DataReceived += MyDataReceivedHandler;
iii
private void Form1_Load(object sender, EventArgs e)
{
iii
private void MyDataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
try
{
//sp.PortName = "COM3";
//sp.Open();
Label1.Text = sp.ReadLine();
iii
catch (Exception exception)
{
RichTextBox1.Text = exception.Message + "
" + exception.Data;
iii
finally
{
sp.Close();
iii
iii
private void button1_Click(object sender, EventArgs e)
{
try
{
sp.PortName = "COM3";
sp.Open();
sp.WriteLine(TextBox1.Text);
iii
catch (Exception exception)
{
RichTextBox1.Text = exception.Message + "
" + exception.Data;
iii
finally
{
sp.Close();
iii
iii
iii
iii