|
-
Jan 17th, 2008, 11:56 AM
#1
Thread Starter
Addicted Member
[2008] Cross-thread operation not valid
Would somone Please explain for me this error
"Cross-thread operation not valid: Control 'lbNames' accessed from a thread other than the thread it was created on."
EVERY TIME I program anything that's related to tcp communication I get this error ALOT
I never was able to understand it...
what does it mean? what are thread operations? they were not found in VB6?
how can I solve this error?
-
Jan 17th, 2008, 12:12 PM
#2
Re: [2008] Cross-thread operation not valid
I showed you how to solve this in the TCP thread.
You can not access a control from a thread other than the thread on which the control was created.
http://www.vbforums.com/showpost.php...4&postcount=17
-
Jan 17th, 2008, 12:48 PM
#3
Thread Starter
Addicted Member
Re: [2008] Cross-thread operation not valid
so for each and every command I have to create a seperate delegate sub and a sperate private sub?
lets say i have this code
Label1.Text = "new"
List1.Items.Add("something")
TextBox1.Text= "solution"
...
so for every single command I have to create a new private sub??
what if I have tens of commands?
this will make my code very large and complex...
-
Jan 17th, 2008, 12:57 PM
#4
Re: [2008] Cross-thread operation not valid
If youre looking to set the Text property of alot of different controls, you can create one routine to handle them all:
Private Delegate SetControlTextDelegate(ByVal ctrl As Control, ByVal text As String)
VB.Net Code:
Private Sub SetControlText(ByVal ctrl As Control, ByVal text As String)
If ctrl.InvokeRequired Then
ctrl.Invoke(New SetControlTextDelegate(AddressOf SetControlText), ctrl, text)
Else
ctrl.Text = text
End If
End Sub
Similar actions can use the same subroutine, if you pass the control to it.
-
Jan 17th, 2008, 01:19 PM
#5
Re: [2008] Cross-thread operation not valid
Microsoft really did make a horrifically poor design decision when they randomly decided to start throwing this error inbetween versions.
-
Jan 17th, 2008, 01:34 PM
#6
Re: [2008] Cross-thread operation not valid
 Originally Posted by Tom Sawyer
Microsoft really did make a horrifically poor design decision when they randomly decided to start throwing this error inbetween versions.
You should've brought that up during the slow-chat in december.
-
Jan 17th, 2008, 01:47 PM
#7
Re: [2008] Cross-thread operation not valid
 Originally Posted by Atheist
You should've brought that up during the slow-chat in december.
Well, they should have made the slow-chat more obvious to see instead of hiding it in big, bold letters at the top of the forum
-
Jan 17th, 2008, 02:07 PM
#8
Thread Starter
Addicted Member
Re: [2008] Cross-thread operation not valid
this was not an error in VB6 right?
why is it now?
-
Jan 17th, 2008, 02:41 PM
#9
Re: [2008] Cross-thread operation not valid
 Originally Posted by perito
this was not an error in VB6 right?
why is it now?
This is the question. They added it into the framework in the 2.0 release, so any applications that used multithreading or timers or anything like that and were built in 1.1 started throwing a bunch of errors when you upgraded them to 2.0 if you were doing anything that involved informing the UI that the child threads had done something.
While there is a potential rationale behind it, in 99% of the cases where it would be thrown, it's a completely pointless error that does nothing but add aggrevation. I can see where it would be useful if you had child threads trying to modify object in other child threads and requiring the developer to call a specific Invoke method in those cases would be good, the change wouldn't be so dumb if they had allowed child threads to continue to have access to the main application's thread's objects without blowing up.
It was just a poor design decision.
-
Jan 17th, 2008, 02:48 PM
#10
Thread Starter
Addicted Member
Re: [2008] Cross-thread operation not valid
Code:
Private Function NickToSend() As String
If Mid(lbNames.Items(lbNames.SelectedIndex).ToString, 1, 1) = "@" Then
NickToSend = Mid(lbNames.Items(lbNames.SelectedIndex).ToString, 2)
Else
NickToSend = lbNames.Items(lbNames.SelectedIndex).ToString
End If
End Function
its throwing the error in the IF STATMENT
If Mid(lbNames.Items(lbNames.SelectedIndex).ToString, 1, 1) = "@" Then
how can I put this in a delegate??
please help
-
Jan 17th, 2008, 03:01 PM
#11
Re: [2008] Cross-thread operation not valid
Actually, it isn't all that dumb. There are some controls in some situations where you can safely make cross-thread calls, but there are other controls where you can never safely make calls like that, and there is no control that I know of where a call like that is ALWAYS safe, race conditions are possible for any control that is ever read. Of course, they could have just let people make the changes and live with the consequences, which is how everything else works in multithreading, but was it really so dumb? As Perito has pointed out, this wasn't an issue in VB6 (because there was no multi-threading in VB6), so people moving over might not understand the implications of the threading model.
There is another alternative to the delegates, but I can't provide an example. Basically it would mean raising events from the background thread to the UI thread. I have a thread on here about something like Synchronization Contexts, which has an example. It's easy enough to do, you would just need to make an event that passed something like the control name and the new setting, then handle those events in the UI thread. Probably not easier than what Atheist posted if you are trying to update controls, but I wasn't dealing with controls at all when I wrote it. I just wanted to raise events in a different thread.
My usual boring signature: Nothing
 
-
Jan 17th, 2008, 03:14 PM
#12
Re: [2008] Cross-thread operation not valid
Yes, it actually was so dumb. In 99% of the cases that would ever occur, having a child thread update an object on the main thread would be a safe operation. The vast majority of uses of that are giving a message with the results, re-enabling buttons, etc.
There is a case for having to use the Invoke to handle events and all between different threads, but I think this error needs to have a check added to see if all that the child thread is doing is updating a UI control or variable that was initialized in the main thread, then ignore the error. It's just pointless complexity that solves nothing and causes unecessary work when errors get thrown for that.
-
Jan 17th, 2008, 03:19 PM
#13
Re: [2008] Cross-thread operation not valid
On further thought, I would agree that it is inconsistent. You can be a bonehead with anything else multi-threaded, so you might as well be able to here. When it works, it would be easier, and when it doesn't....well, you should be aware of what you are doing in those situations. Multithreading bugs are a royal pain to track down, cause half the time it starts with a wild guess as to what the problem is, but if you are updating a label, then odds of a race condition are very small.
My usual boring signature: Nothing
 
-
Jan 17th, 2008, 03:26 PM
#14
Re: [2008] Cross-thread operation not valid
You could disable the cross-thread exceptions if you dont like them (Personally I find them amusing).
VB.Net Code:
CheckForIllegalCrossThreadCalls = False
-
Jan 17th, 2008, 03:32 PM
#15
Re: [2008] Cross-thread operation not valid
That's kind of the point I was trying to make.
If you're doing complex multi-threaded functionality, then you're going to need to do all the extra work and checks anyways, or you're going to have far more problems than you'd ever get by trying to change a label value from two threads at once.
If you're doing the simple type of multi-threading that is merely designed to not have forms freeze up when some operation is running or having a timer kick off some process, then it's a pointless check that does nothing but add unecessary complexity to a simple operation and doesn't offer any real benefit.
Also, there's the fact that they decided to make this an error between two releases, so things that worked in 1.1 started throwing strange errors as soon as you upgraded. That really annoyed me and I've been taking the opportunity to ***** about it every chance I can get ever since.
-
Jan 17th, 2008, 03:34 PM
#16
Re: [2008] Cross-thread operation not valid
-
Jan 17th, 2008, 03:36 PM
#17
Re: [2008] Cross-thread operation not valid
 Originally Posted by Atheist
You could disable the cross-thread exceptions if you dont like them (Personally I find them amusing).
VB.Net Code:
CheckForIllegalCrossThreadCalls = False
Well, that makes things easier.
I wish I'd seen that property before.
-
Jan 17th, 2008, 03:37 PM
#18
Re: [2008] Cross-thread operation not valid
I personally dont think the MS team would add something to the .Net framework without really thinking through it. Anyhow, we shouldnt be hijacking this thread any longer.
-
Jan 17th, 2008, 03:38 PM
#19
Thread Starter
Addicted Member
Re: [2008] Cross-thread operation not valid
 Originally Posted by perito
Code:
Private Function NickToSend() As String
If Mid(lbNames.Items(lbNames.SelectedIndex).ToString, 1, 1) = "@" Then
NickToSend = Mid(lbNames.Items(lbNames.SelectedIndex).ToString, 2)
Else
NickToSend = lbNames.Items(lbNames.SelectedIndex).ToString
End If
End Function
its throwing the error in the IF STATMENT
If Mid(lbNames.Items(lbNames.SelectedIndex).ToString, 1, 1) = "@" Then
how can I put this in a delegate??
please help
can anyone help me with this one? please
-
Jan 17th, 2008, 03:40 PM
#20
Re: [2008] Cross-thread operation not valid
What error are you getting? You should really be using SubString instead of Mid().
-
Jan 17th, 2008, 03:43 PM
#21
Thread Starter
Addicted Member
Re: [2008] Cross-thread operation not valid
Im getting
Cross-thread operation not valid: Control 'lbNames' accessed from a thread other than the thread it was created on
in the first line of the if statment (If Mid(lbNames.Items(lbNames.SelectedIndex).ToString, 1, 1) = "@" Then)
how to put a delegate in an if statment?
anyway why is SubString better than Mid? I donno what SubString is... Ill google it now :P
-
Jan 17th, 2008, 03:51 PM
#22
Re: [2008] Cross-thread operation not valid
try adding:
lblNames.CheckForIllegalCrossThreadCalls = false
before your IF statement. That should handle it.
Also, I just saw that using a BackgroundWorker thread automatically handles invoking methods on the correct UI thread, so that would probably work, too, instead of just running it in a regular thread.
-
Jan 17th, 2008, 04:04 PM
#23
Re: [2008] Cross-thread operation not valid
Substring is simply a method of the string class. Mid() is an old basic function only included in .Net for legacy support.
See here:
VB.Net Code:
Dim originString As String = "Hello"
Dim partString As String = Mid(originString,1,2)
'partString will contain "he"
The substring equivalent is:
VB.Net Code:
Dim originString As String = "Hello"
Dim partString As String = originString.SubString(0,2)
'partString will contain "he"
Now, in order to call the NickToSend() from the separate thread we first need to create a function delegate:
VB.Net Code:
Private Delegate Function DelegateStringFunction() As String
Then, calling the method would look like this:
VB.Net Code:
Dim nick As String = CStr(lbNames.Invoke(New DelegateStringFunction(AddressOf NickToSend)))
We invoke the NickToSend function to run in the same thread that lbNames was created on.
-
Jan 17th, 2008, 04:17 PM
#24
Re: [2008] Cross-thread operation not valid
 Originally Posted by Tom Sawyer
try adding:
lblNames.CheckForIllegalCrossThreadCalls = false
before your IF statement. That should handle it.
Also, I just saw that using a BackgroundWorker thread automatically handles invoking methods on the correct UI thread, so that would probably work, too, instead of just running it in a regular thread.
While I understand your position posted previously, this is NOT the place to be ignoring cross threaded calls because the OP is checking the value in the label prior to changing it. If this is the ONLY thread that is altering the value of the label, then he's safe, otherwise, by disabling cross thread call checking in this case, he opens himself up to race conditions, and those are a nightmare to figure out, especially if you have been trying to ignore the implications of threading.
If he was only writing, that would be one thing, but when he branches on the current state, then race conditions enter the picture. A context switch right after the If statement would result in an incorrect return. This may not be a problem, but WE certainly can't tell.
My usual boring signature: Nothing
 
-
Jan 17th, 2008, 04:22 PM
#25
Re: [2008] Cross-thread operation not valid
 Originally Posted by Shaggy Hiker
While I understand your position posted previously, this is NOT the place to be ignoring cross threaded calls because the OP is checking the value in the label prior to changing it. If this is the ONLY thread that is altering the value of the label, then he's safe, otherwise, by disabling cross thread call checking in this case, he opens himself up to race conditions, and those are a nightmare to figure out, especially if you have been trying to ignore the implications of threading.
If he was only writing, that would be one thing, but when he branches on the current state, then race conditions enter the picture. A context switch right after the If statement would result in an incorrect return. This may not be a problem, but WE certainly can't tell.
Yes, as I said previously, this error message is unecessary in 99% of the cases.
-
Jan 17th, 2008, 04:24 PM
#26
Re: [2008] Cross-thread operation not valid
True, but this is not the case. Ignoring the error means ignoring a potentially aggravating bug.
My usual boring signature: Nothing
 
-
Jan 18th, 2008, 09:36 AM
#27
Re: [2008] Cross-thread operation not valid
 Originally Posted by Shaggy Hiker
True, but this is not the case. Ignoring the error means ignoring a potentially aggravating bug.
In the case that you are mentioning, that is true. As I said above, if you're doing this type of complex multi-threading, you need to take this sort of thing into account or the error that's coming up will be the least of your worries.
The other 99% of the time, such as in instances that the OP is talking about, nothing like this is a worry and it just adds needless complexity to control for a potential situation that isn't actually a potential problem in the application. True, that's why simple apps doing things like that should use a BackgroundWorker thread instead of just creating a regular child thread, but the arbitrariness with which this error started being included inbetween versions to deal with an issue that wasn't even an issue was just annoying as hell.
-
Jan 18th, 2008, 04:43 PM
#28
Re: [2008] Cross-thread operation not valid
Multi-threading has spawned more interesting arguments and discussions than any other similar topic that I am aware of. I have read raging debates over whether or not it is even possible to make a truly thread-safe process, or whether every technique leaves some loophole that somebody could squeeze through. I suspect that MS tried a half-hearted attempt to push threading towards more safety by forcing people to consider thread safety for this one scenario. I agree that the solution is far less than ideal in that you are totally on your own in every other way, yet they try to put constraints on you in this one area, and do it in a way that is hardly sufficient and not always necessary.
However, threading is actually really easy to accomplish, especially if you don't care about it working well. I think they could have come up with a VASTLY improved architecture if they really wanted VB to be a very user friendly programming environment. For example, it seems like they might have been able to add some kind of keyword such as ThreadShared to any object, and have the compiler implement synch locking on that object for any thread that used the object. That would leave open the option of deadlocks, but perhaps the IDE could structure threads into separate routines such that deadlock potential could be tracked more readily.
Ultimately, we are moving towards increased advantage from multithreading, especially as all computers have increasing numbers of processors or cores. Multi-threading is one area that has been left up to the programmer entirely, so far, and this half-assed step might be the first fitful sign that MS has recognized that multi-threading, with all its intense complexity, will become increasingly mainstream. It wasn't well done, but perhaps it is a start.
My usual boring signature: Nothing
 
-
Jan 18th, 2008, 08:49 PM
#29
Re: [2008] Cross-thread operation not valid
Not that I recommend this but if you don't want the debugger to enforce calls being made from the appropriate thread then it takes one line of code:
vb.net Code:
Control.CheckForIllegalCrossThreadCalls = False
That's all you have to do instead of talking rubbish about dumb decisions and arbitrary errors when the decision wasn't dumb and the errors aren't arbitrary. Tom Sawyer, you don't really understand this topic. That's no shame but it's best to make sure you do before making such bold statements.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|