tags:

views:

196

answers:

2

I've migrated a .Net legacy .Net project from .Net 1.1 to .Net 3.5 and when I try and run it I'm getting the following error:

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

When the a thread (Which I assume is not the UI thread) changes the enabled property of a button to true.

I reckon something changed in the framework to add this restriction, is there a way to make this work without overhauling the entire app?

Can I make VS (I'm using VS 2008)run the App as .Net 1.1 (I'm not even sure that this is the problem)

The application is merely a test application for an API which I've been told to reverse engineer, so and I don't really have the bandwidth to fix all it's issues. I know it worked previously but I don't have an old version of VS installed so I had to convert it over to VS 2008.

A: 

Found Fix here solution is to use annonomous delegates:

 // running on worker thread...
  string newText = LongRunningOperation();

  //switch to UI thread
  this.Invoke((MethodInvoker)delegate {
    // this bit runs on the UI thread
    this.Text = newText;
  });

Obviously replace "this.Text" with whatever code you want to run in UI thread, works a charm.

Still interested in a way to run as .Net 1.1 under VS 2008 I heard that you can run multiple F/Work versions in it, just don't know how.

I've started addign the annonomous delegates to anywhere there is UI code to fix this issue.

Omar Kooheji
+1  A: 

The fix isn't to use anonymous methods: it's just to use Control.Invoke or Control.BeginInvoke in some way. It doesn't matter whether it's an anonymous method, a delegate created from a method group or a lambda expression - the point is that you need to marshal over to the UI thread. See my threading article for more details. You might also want to consider using BackgroundWorker to make it easier. (My article was written before .NET 2.0, hence its lack of BackgroundWorker references.)

This was already a bug in your 1.1 code, by the way - this isn't a new restriction in .NET 2.0, it's just that .NET 2.0 added a check (throwing the exception you've seen) when running in debug mode.

Jon Skeet