-1

I performed a genetic algorithm that loops 10 times where each time I call the "FitnessFunction" function, I use a background worker to move an object on the topology and once it reach a specific point then I cancel that background worker and back to the "Genetic_Algorithm" function...

Unfortunately, I got the following error:

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

What I have tried:

Run the background worker each time I call "FitnessFunction" function" which is responsible to stop it under a specific condition.

Rose
  • 349
  • 3
  • 17
  • You should look into using the `ReportProgress()` function that raises an event on the UI thread where you can update controls. Otherwise calls to UI controls must be marshaled to the UI thread where they were created. https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.reportprogress(v=vs.110).aspx – xxbbcc May 15 '17 at 21:07
  • @xxbbcc : could you put an answer ? – Rose May 15 '17 at 21:22

1 Answers1

0

WinForms forbids to access Controls from other threads than the main UI.

Use Invoke(..) method of the form or use SynchronizationContext class.

private SynchronizationContext context;

MyForm()
{
  InitializeComponents();
  context = SynchronizationContext.Current;
}

///// somewhere in another thread
context.Post(myCallbackInUIThread, null) // you can use Send for synchronous call
rattler
  • 379
  • 2
  • 5
  • 15
  • how to fix while(true) , how to use invoke there? could you complete your answer ? – Rose May 15 '17 at 21:07
  • The exception is thrown when you're trying to draw on control from non-UI-thread (worker). Wrap drawing operations in another method and call it via Invoke/Post. – rattler May 15 '17 at 22:11