The Problem :
- You are writing a windows application
- You make an asynchronous webservice call (or you launch a background worker thread to get some data)
- m_WebService1.FuncAsync() ‘If you are using VB.Net you probably have a member variable declared for the webservice and you are calling the MethodXXXAsync() function generated by Visual Studio when you added the WebReference.
- In your m_WebService1_MethodXXCompleted() event handler, you try to update the User Interface (eg. txtBox.text = value)
- At this point the screen blows up and you get the dreaded error :
Cross-thread operation not valid: Control ‘Form1’ accessed from a thread other than the thread it was created on
- If you are from the old COM/COM+ Days, you must remember that an STA (Single Threaded Apartment) can only be accessed by the thread that originally created it. All the controls on the form are created by the main thread of the application, so only the main thread can update it. When your asynch webservice call returns it is calling the MethodXXCompleted() event handler in the context of a different thread. This thread is not allowed to touch any controls on the form
The Solution :
- From the Asynch event handler, you need to invoke the function which will update the UI from the context of the original thread.
- Say, the function which will update the UI is called Private Sub UpdateApps(), you need to declare a delegate for this function. Later we invoke this delegate (see step2 to do the actual work). You cannot call this function directly because it will still happen in the context of the second thread and you will get the same error.
That should take care of the problem. JAdvertisements