473,387 Members | 1,703 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Cross Threading error????

I run this code:
Private Sub p_recv(ByVal sender As Object, ByVal e As
SerialReceivedEventArgs) Handles p.ReceivedEvent
txtRecv.Text += p.ReadExisting
End Sub

I get this error:

--------------------ERROR TEXT--------------------
Illegal cross-thread operation: Control 'txtRecv' accessed from a thread
other than the thread it was created on.
Stack trace where the illegal operation occurred was:

at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.get_WindowText()
at System.Windows.Forms.TextBoxBase.get_WindowText()
at System.Windows.Forms.Control.get_Text()
at System.Windows.Forms.TextBoxBase.get_Text()
at System.Windows.Forms.TextBox.get_Text()
at ComPortTest.Form1.p_recv(Object, SerialReceivedEventArgs)
at System.IO.Ports.SerialPort.CatchReceivedEvents(Obj ect,
SerialReceivedEventArgs)
at System.IO.Ports.SerialStream.EventLoopRunner.CallR eceiveEvents(Object)
at System.Threading._ThreadPoolWaitCallback.WaitCallb ack_Context(Object)
at System.Threading.ExecutionContext.Run(ExecutionCon text, ContextCallback,
Object, StackCrawlMark&)
at System.Threading._ThreadPoolWaitCallback.WaitCallb ack(Object)
---------------END ERROR TEXT-----------------------

Evidently, the function I'm calling creates a thread. So how can I write to
the textbox from the function without getting this error?
Nov 21 '05 #1
7 4048
Windows forms controls are not thread safe. You cannot update them from a
different thread then they are running on. Take a look at this article to
get an idea of how to do it:

http://www.codenotes.com/articles/ar...?articleID=515

"Terry Olsen" <to******@hotmail.com> wrote in message
news:uS**************@tk2msftngp13.phx.gbl...
I run this code:
Private Sub p_recv(ByVal sender As Object, ByVal e As
SerialReceivedEventArgs) Handles p.ReceivedEvent
txtRecv.Text += p.ReadExisting
End Sub

I get this error:

--------------------ERROR TEXT--------------------
Illegal cross-thread operation: Control 'txtRecv' accessed from a thread
other than the thread it was created on.
Stack trace where the illegal operation occurred was:

at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.get_WindowText()
at System.Windows.Forms.TextBoxBase.get_WindowText()
at System.Windows.Forms.Control.get_Text()
at System.Windows.Forms.TextBoxBase.get_Text()
at System.Windows.Forms.TextBox.get_Text()
at ComPortTest.Form1.p_recv(Object, SerialReceivedEventArgs)
at System.IO.Ports.SerialPort.CatchReceivedEvents(Obj ect,
SerialReceivedEventArgs)
at System.IO.Ports.SerialStream.EventLoopRunner.CallR eceiveEvents(Object)
at System.Threading._ThreadPoolWaitCallback.WaitCallb ack_Context(Object)
at System.Threading.ExecutionContext.Run(ExecutionCon text, ContextCallback, Object, StackCrawlMark&)
at System.Threading._ThreadPoolWaitCallback.WaitCallb ack(Object)
---------------END ERROR TEXT-----------------------

Evidently, the function I'm calling creates a thread. So how can I write to the textbox from the function without getting this error?

Nov 21 '05 #2
Hey thanks! That helped. Here's the code that works.

Private Delegate Sub TextBoxInvoker(ByVal txt As String)

Private Sub p_recv(ByVal sender As Object, ByVal e As
SerialReceivedEventArgs) Handles p.ReceivedEvent
Dim txt As String = p.ReadExisting
txtRecv.Invoke(CType(AddressOf UpdateTextBox, TextBoxInvoker), txt)
End Sub

Private Sub UpdateTextBox(ByVal txt As String)
txtRecv.Text += txt
End Sub
"Ray Cassick (Home)" <rc************@enterprocity.com> wrote in message
news:u0**************@TK2MSFTNGP12.phx.gbl...
Windows forms controls are not thread safe. You cannot update them from a
different thread then they are running on. Take a look at this article to
get an idea of how to do it:

http://www.codenotes.com/articles/ar...?articleID=515

Nov 21 '05 #3
On 2004-11-20, Terry Olsen <to******@hotmail.com> wrote:
Hey thanks! That helped. Here's the code that works.

Private Delegate Sub TextBoxInvoker(ByVal txt As String)

Private Sub p_recv(ByVal sender As Object, ByVal e As
SerialReceivedEventArgs) Handles p.ReceivedEvent
Dim txt As String = p.ReadExisting
txtRecv.Invoke(CType(AddressOf UpdateTextBox, TextBoxInvoker), txt)
End Sub

Private Sub UpdateTextBox(ByVal txt As String)
txtRecv.Text += txt
End Sub


That's one way, or you can just invoke your method again...

Private Sub p_recv (ByVal sender As Object, ByVal e As
SerialRecievedEventArgs) Handles p.ReceivedEvent

If txtRecv.InvokeRequired Then
txtRecv.Invoke (AddressOf p_recv, new Object() {sender, e})
Else
txtRecv.Text += p.ReadExisting
End If
End Sub
--
Tom Shelton [MVP]
Nov 21 '05 #4
I also just discovered the "TextBox.AppendText" method. More elegant than
TextBox.Text += "NewText"

"Tom Shelton" <to*@YOUKNOWTHEDRILLmtogden.com> wrote in message
news:%2****************@TK2MSFTNGP11.phx.gbl...
On 2004-11-20, Terry Olsen <to******@hotmail.com> wrote:
Hey thanks! That helped. Here's the code that works.

Private Delegate Sub TextBoxInvoker(ByVal txt As String)

Private Sub p_recv(ByVal sender As Object, ByVal e As
SerialReceivedEventArgs) Handles p.ReceivedEvent
Dim txt As String = p.ReadExisting
txtRecv.Invoke(CType(AddressOf UpdateTextBox, TextBoxInvoker), txt)
End Sub

Private Sub UpdateTextBox(ByVal txt As String)
txtRecv.Text += txt
End Sub


That's one way, or you can just invoke your method again...

Private Sub p_recv (ByVal sender As Object, ByVal e As
SerialRecievedEventArgs) Handles p.ReceivedEvent

If txtRecv.InvokeRequired Then
txtRecv.Invoke (AddressOf p_recv, new Object() {sender, e})
Else
txtRecv.Text += p.ReadExisting
End If
End Sub
--
Tom Shelton [MVP]

Nov 21 '05 #5
Hello Tom. I was trying your method in the following code, but I get this
error in design time;
"'AddressOf' expression cannot be converted to 'System.Delegate' because
'System.Delegate' is not a delegate type"
Any Ideas??? Also, would this even work? It seems as if it might be trying
to read data into myBuffer twice (2nd time when the invoke occurrs).
Thanks!

Private Sub myListener_DataArrival() Handles myListener.DataArrival
Debug.Print("DataArrival Event")
Dim myBuffer() As Byte = New Byte() {}
myListener.ReadData(myBuffer)
If txtReceive.InvokeRequired Then
txtReceive.Invoke(AddressOf myListener_DataArrival) 'Error
occurrs here.
Else
txtReceive.AppendText(System.Text.Encoding.ASCII.G etString(myBuffer))
End If
End Sub

"Tom Shelton" <to*@YOUKNOWTHEDRILLmtogden.com> wrote in message
news:%2****************@TK2MSFTNGP11.phx.gbl...
On 2004-11-20, Terry Olsen <to******@hotmail.com> wrote:
Hey thanks! That helped. Here's the code that works.

Private Delegate Sub TextBoxInvoker(ByVal txt As String)

Private Sub p_recv(ByVal sender As Object, ByVal e As
SerialReceivedEventArgs) Handles p.ReceivedEvent
Dim txt As String = p.ReadExisting
txtRecv.Invoke(CType(AddressOf UpdateTextBox, TextBoxInvoker), txt)
End Sub

Private Sub UpdateTextBox(ByVal txt As String)
txtRecv.Text += txt
End Sub


That's one way, or you can just invoke your method again...

Private Sub p_recv (ByVal sender As Object, ByVal e As
SerialRecievedEventArgs) Handles p.ReceivedEvent

If txtRecv.InvokeRequired Then
txtRecv.Invoke (AddressOf p_recv, new Object() {sender, e})
Else
txtRecv.Text += p.ReadExisting
End If
End Sub
--
Tom Shelton [MVP]

Nov 21 '05 #6
On 2004-11-27, Terry Olsen <to******@hotmail.com> wrote:
Hello Tom. I was trying your method in the following code, but I get this
error in design time;
"'AddressOf' expression cannot be converted to 'System.Delegate' because
'System.Delegate' is not a delegate type"
Any Ideas??? Also, would this even work? It seems as if it might be trying
to read data into myBuffer twice (2nd time when the invoke occurrs).
Thanks!

Private Sub myListener_DataArrival() Handles myListener.DataArrival
Debug.Print("DataArrival Event")
Dim myBuffer() As Byte = New Byte() {}
myListener.ReadData(myBuffer)
If txtReceive.InvokeRequired Then
txtReceive.Invoke(AddressOf myListener_DataArrival) 'Error
occurrs here.
Else
txtReceive.AppendText(System.Text.Encoding.ASCII.G etString(myBuffer))
End If
End Sub


First of all... Are you using one of the standard .NET classes? Because
none of those have a DataArrival event that I recall. I use this
technique all the time for async and multithreaded calls, so I know it
works..

Anyway, part of the problem would be your structure as well... You
would want to move the code that does the reading inside the else block:

If txtRecieve.InvokeRequired Then
' invoke the method
Else
' dim your buffer
' read the data
' append the text
End If
--
Tom Shelton [MVP]
Nov 21 '05 #7
Tom,

I'm trying to use this code...but I'm having some problems.

I'm trying to call a Button.PerformClick method from an event handler that
is called from another thread.

Private Sub ConnectionDroppedEvent() Handles myListener.ConnectionDropped
That's one way, or you can just invoke your method again...

Private Sub p_recv (ByVal sender As Object, ByVal e As
SerialRecievedEventArgs) Handles p.ReceivedEvent

If txtRecv.InvokeRequired Then
txtRecv.Invoke (AddressOf p_recv, new Object() {sender, e})
Else
txtRecv.Text += p.ReadExisting
End If
End Sub
--
Tom Shelton [MVP]

Nov 21 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: rob | last post by:
Dear All, I am getting an error "Illegal cross-thread operation". I am not creating any threads. I know internally there are many threads running, though. Does that mean that no form can call a...
12
by: Wilfried Mestdagh | last post by:
Hi, Using P/Invoke I use PostMessage to send a message from one thread to another. I'm pretty sure this has already worked in dotnet. but I've upgraded version 2 few day ago. Now I have an...
2
by: genojoe | last post by:
In simplified form, I have an RTF control and a timer. I use the timer to do an autoresave for the RFT control every 5 minutes. Here is the abridged code. Private Sub tmrAutoRecover_Tick(ByVal...
2
by: m.lancashire | last post by:
I have a dotnet 2.0 web service method that I execut asynchronously using the auto generated method. I catch the event using this Private Sub Event_Completed(ByVal sender As Object _ , ByVal e As...
11
by: HairlipDog58 | last post by:
Hello, There are several 'cross-thread operation not valid' exception postings in the MSDN discussion groups, but none address my exact situation. I have authored a .NET component in Visual C#...
5
by: Rob R. Ainscough | last post by:
I'm using a BackgroundWorker to perform a file download from an ftp site. Per good code design practices where I separate my UI code from my core logic code (in this case my Download file method in...
5
by: JasonX | last post by:
Im having problems with my program, in that if I close the main form while my new thread is doing work which involves writing to the main form, then I get an error about a disposed object. To...
2
by: cpix | last post by:
hi! i've been reading alot about the backgroundworker, but most of the articals only shows that you can use the progress-event to send a message to the form. Im trying to pass a listview with a...
2
by: bhupendrakumar | last post by:
error message System.InvalidOperationException was unhandled Message="Cross-thread operation not valid: Control 'listView2' accessed from a thread other than the thread it was created on." ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.