56302

Main UI windows not updating control -Cross-thread operation not valid

Question:

Ok..here is the problem

I have a main UI form that has a control container that i can add some buttons item to it,and also i have a backgroundworker object that starts up a listner. When the listner events fire, i would like to create a button in that control container on the main UI form. Everything seems to work fine until i try to add a new control item to that container. I get the following exception

"Cross-thread operation not valid: Control 'RadMagnifier_AcceptReject' accessed from a thread other than the thread it was created on."

the code flows like this

Private Sub Mainform_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Me.SessionTableAdapter.Fill(Me.BCSSDataSet1.Session) FormatColumns() Me.BackgroundWorker2.RunWorkerAsync() End Sub Private Sub BackgroundWorker2_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker2.DoWork Notifications() End Sub Private Sub Notifications() 'Start listing for events when event is fired try to add a button to a controls container on the UI thread, and that when i get the problem End Sub

Answer1:

Assuming you moved all UI operations into the RunWorkerCompleted method, it looks like a bug:

<a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=116930" rel="nofollow">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=116930</a> <a href="http://thedatafarm.com/devlifeblog/archive/2005/12/21/39532.aspx" rel="nofollow">http://thedatafarm.com/devlifeblog/archive/2005/12/21/39532.aspx</a>

I suggest using the bullet-proof (pseudocode):

if(control.InvokeRequired) control.Invoke(Action); else Action()

Answer2:

You should check out the follow article

<a href="http://msdn.microsoft.com/en-us/library/ms171728.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms171728.aspx</a>

and for more in-depth information read this

<a href="http://weblogs.asp.net/justin_rogers/pages/126345.aspx" rel="nofollow">http://weblogs.asp.net/justin_rogers/pages/126345.aspx</a>

Answer3:

You cannot update UI elements from other threads other than the UI thread.

Add the button add code to RunWorkerCompleted Event, since that will be fired on the UI thread. The DoWork event runs on a thread pool thread not on the UI thread.

Answer4:

You have to use the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.runworkercompleted.aspx" rel="nofollow">RunWorkerCompleted</a> event because it is executed on the UI thread. Adding controls on the form from the DoWork event is wrong because this function is executed on a different thread than the one that created the main form.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Me.BackgroundWorker1.RunWorkerAsync() End Sub Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork Thread.Sleep(1000) 'Do not modify the UI here!!! End Sub Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted Me.Controls.Add(New Button()) End Sub

Answer5:

Hmm..when i move the Notification procedure into the RunworkerCompleted event it gives me the same error. I cant add the button in the RunworkerCompleted event directly because the Notification procedure is wait for event to happen before creating the new button.

Here is a more clear example

Private Sub Notifications() Dim NotificationObj As New NotificationEngine()

' register a handler to listen for receive events AddHandler Noification.ReceiveCompleted, AddressOf NotificationReceive ' start the notification processor NotificationObj.Start() End Sub

And then once the NotificationReceive event fires thats when i create a new button and add it to the controls container on the main form.

Answer6:

You could use Control.BeginInvoke, calling it on your form, from the background thread, passing a deleate to add the new button.

Recommend

  • Pass values from BackgroundWorker DoWork to BackgroundWorker Completed
  • set size of a base64 image javascript - angularjs
  • WCF and ASP.NET - Server.Execute throwing object reference not set to an instance of an object
  • Background Worker Delphi
  • Track WordPress Signups with Google Analytics
  • PySpark job hangs forever (during real-time analysis)
  • invoke during background worker
  • multiple backgroundworker queueing
  • Elasticsearch QueryStrings: partially match a NOT query?
  • Creating an array of products in JSON-LD
  • Error handling in Q promise
  • synchronous AJAX post from unload event: how to ensure user sees most up-to-date information from DB
  • Adding libraries to portable python
  • Way to represent unknown file size in FTP LIST?
  • Suspending and notifying threads when there is work to do
  • How to pass multiple parameters to a thread function
  • C#, Updating a Progress Bar Using Background Worker From a Different Class
  • Celery + Redis - .get() hangs indefinitely after running smoothly for ~70 hours
  • What is happening when this code calls FUSE like this?
  • Android GCM push notification without server OR GCM push notification using Microsoft SQL(Not Mysql)
  • Syncronizing database from Active Directory
  • how to reopen a class in gems
  • Can my app be notified when another application starts/stops playing audio?
  • Enumerating Controls on a Form
  • How can I tell a form not to dispose a particular control when it closes?
  • WPF version of .ScaleControl?
  • Overlapping controls in Windows XP
  • IE7 and TinyMCE with Plone
  • presentShareDialogWithParams posts to FB wall, but callback handler results say error
  • AJAX Html Editor Extender upload image appearing blank
  • d3 v4 drag and drop with TypeScript
  • JQuery Internet Explorer and ajaxstop
  • Debugging ASP.NET on a built-in web server suddenly stops
  • Opengl-es onTouchEvents problem or a draw problem? [closed]
  • Python - Map / Reduce - How do I read JSON specific field in using DISCO count words example
  • using conditional logic : check if record exists; if it does, update it, if not, create it
  • python regex in pyparsing
  • Android Google Maps API OnLocationChanged only called once
  • Linking SubReports Without LinkChild/LinkMaster
  • How can I use threading to 'tick' a timer to be accessed by other threads?