How to run the same background worker and stop it inside a loop in C#

142 views Asked by At

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.

1

There are 1 answers

2
rattler On

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