Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to see the received data into the richTextbox but i am getting an exception that,cross thread is not allowed.Please can anyone give me that small code.I am new to threading.

What I have tried:

I am getting cross threading exception.
Posted
Updated 22-Jan-18 20:50pm
Comments
Member 13325846 3-Mar-18 5:21am    
Hi,
May you help me to send my data that are writing in every 63seconds in a text file
to another computer using com port.
i'll be thankful.

1 solution

Hi,

This is an old and commonly asked question. What you are seeing is that your data from the serial port is being received on another thread. The thread that is running the Windows UI is different. It's like two different machines running in the same house, but one has no idea how to deal with the other.

So you need what's called a delegate.

See the code below.


// I've named this 'StringDelegate' - returns void and carries a string.
delegate void StringDelegate(string text); 


// Look at your rich text box, use the rich text box control's 
// name property in place where I have written 'richTextBox1'


//
// Call this method directly with the 
// data from your Serial port.
//
private void SetText(string text)  
{  
    // InvokeRequired required compares the thread ID of the  
    // calling thread to the thread ID of the creating thread.  
    // If these threads are different, it returns true.  
    if (this.richTextBox1.InvokeRequired)  
    {     

        StringArgReturningVoidDelegate d = new StringArgReturningVoidDelegate(SetText);  
        this.Invoke(d, new object[] { text });  
    }  
    else  
    {  
        this.richTextBox1.Text = text;  
    }  
}  
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900