Results 1 to 29 of 29

Thread: [2008] Cross-thread operation not valid

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    [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?

  2. #2
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    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
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    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...

  4. #4
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    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:
    1. Private Sub SetControlText(ByVal ctrl As Control, ByVal text As String)
    2.     If ctrl.InvokeRequired Then
    3.         ctrl.Invoke(New SetControlTextDelegate(AddressOf SetControlText), ctrl, text)
    4.     Else
    5.         ctrl.Text = text
    6.     End If
    7. End Sub

    Similar actions can use the same subroutine, if you pass the control to it.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  5. #5
    Frenzied Member
    Join Date
    May 2006
    Location
    Toronto, ON
    Posts
    1,093

    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.

  6. #6
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2008] Cross-thread operation not valid

    Quote 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.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  7. #7
    Frenzied Member
    Join Date
    May 2006
    Location
    Toronto, ON
    Posts
    1,093

    Re: [2008] Cross-thread operation not valid

    Quote 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

  8. #8

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Cross-thread operation not valid

    this was not an error in VB6 right?
    why is it now?

  9. #9
    Frenzied Member
    Join Date
    May 2006
    Location
    Toronto, ON
    Posts
    1,093

    Re: [2008] Cross-thread operation not valid

    Quote 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.

  10. #10

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    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

  11. #11
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    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

  12. #12
    Frenzied Member
    Join Date
    May 2006
    Location
    Toronto, ON
    Posts
    1,093

    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.

  13. #13
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    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

  14. #14
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    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:
    1. CheckForIllegalCrossThreadCalls = False
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  15. #15
    Frenzied Member
    Join Date
    May 2006
    Location
    Toronto, ON
    Posts
    1,093

    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.

  16. #16
    Frenzied Member
    Join Date
    May 2006
    Location
    Toronto, ON
    Posts
    1,093

    Re: [2008] Cross-thread operation not valid

    <never mind>

  17. #17
    Frenzied Member
    Join Date
    May 2006
    Location
    Toronto, ON
    Posts
    1,093

    Re: [2008] Cross-thread operation not valid

    Quote Originally Posted by Atheist
    You could disable the cross-thread exceptions if you dont like them (Personally I find them amusing).
    VB.Net Code:
    1. CheckForIllegalCrossThreadCalls = False
    Well, that makes things easier.

    I wish I'd seen that property before.

  18. #18
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    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.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  19. #19

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Cross-thread operation not valid

    Quote 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

  20. #20
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2008] Cross-thread operation not valid

    What error are you getting? You should really be using SubString instead of Mid().
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  21. #21

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    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

  22. #22
    Frenzied Member
    Join Date
    May 2006
    Location
    Toronto, ON
    Posts
    1,093

    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.

  23. #23
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    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:
    1. Dim originString As String = "Hello"
    2. Dim partString As String = Mid(originString,1,2)
    3. 'partString will contain "he"

    The substring equivalent is:
    VB.Net Code:
    1. Dim originString As String = "Hello"
    2. Dim partString As String = originString.SubString(0,2)
    3. '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:
    1. Private Delegate Function DelegateStringFunction() As String
    Then, calling the method would look like this:

    VB.Net Code:
    1. 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.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  24. #24
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    Re: [2008] Cross-thread operation not valid

    Quote 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

  25. #25
    Frenzied Member
    Join Date
    May 2006
    Location
    Toronto, ON
    Posts
    1,093

    Re: [2008] Cross-thread operation not valid

    Quote 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.

  26. #26
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    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

  27. #27
    Frenzied Member
    Join Date
    May 2006
    Location
    Toronto, ON
    Posts
    1,093

    Re: [2008] Cross-thread operation not valid

    Quote 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.

  28. #28
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    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

  29. #29
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    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:
    1. 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.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width