Link to home
Start Free TrialLog in
Avatar of ross13
ross13Flag for United Kingdom of Great Britain and Northern Ireland

asked on

Help with Cross-thread operation not valid

I have a simple application that is monitoring a folder in VB.NET.
When a file is dropped into the folder I want the buttons on the form to become enabled. When I try to access the buttons on the form to enable them I receive the following error message.

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






Sub onChanged(ByVal from As Object, ByVal e As FileSystemEventArgs) Handles watcher.Created
 
       btnExtractXML.Enabled = False
       txtPickFile.Enabled = True
       btnPickFile.Enabled = True
       btnRun.Enabled = True
 
    End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Dirk Haest
Dirk Haest
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The BackgroundWorker class makes this kind of thing very simple. It does all the marshalling to the UI thread for you.

http://msdn2.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx


To use winforms control from separate thread you should call Control.Invoke method. In your case this will be TextBox.Invoke
 
The code may look like this:
 
delegate void OutputUpdateDelegate(string data);
public void UpdateTextBox(string data)
{
if ( txtOutput.InvokeRequired )
  txtOutput.Invoke(new OutputUpdateDelegate(OutputUpdateCallback),
  new object[] { data });
else
  OutputUpdateCallback(data); //call directly
}
 
private void OutputUpdateCallback(string data)
{
 txtOutput.Text += data;
}
 
UpdateTextBox method can be called from other threads 

Open in new window

You can't access the form's controls through other threads than the one who created it. You can fix it by calling invoke.

Example of using an invoke and delegate can be found here:
How can I update my user interface from a thread that did not create it?
http://blogs.msdn.com/csharpfaq/archive/2004/03/17/91685.aspx

Update UI the easy way using anonymous delegates
http://staceyw.spaces.live.com/blog/cns!F4A38E96E598161E!652.entry
Perhaps you should take a look at this article: Updating the UI from a Secondary Thread
http://msdn.microsoft.com/en-us/magazine/cc188732.aspx
http://weblogs.asp.net/justin_rogers/articles/126345.aspx
It looks like your FileSystemWatcher is called "watcher":

    Sub onChanged(ByVal from As Object, ByVal e As FileSystemEventArgs) Handles watcher.Created

How and where from are you creating it?  What is the entry point into your application?  Can you show us some code?