c#


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


This question already has an answer here:
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on
16 answers
I wrote the following code to perform genetic algorithm that loops 10 times and 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...
My Windows Form Application Main Form
Unfortunately, I got the following error when I click on "MOVE-AUV-GAAPS" button which call the "Genetic_Algorithm" method:
Cross-thread operation not valid: Control 'topology' accessed from a thread other than the thread it was created on...
and point to:
while(true)
which is in the "AUVbackGWgenetic_DoWork" function.
"Genetic_Algorithm" function :
static int geneticIteration;
 
static BackgroundWorker AUVbackGWgenetic;
 
public void Genetic_Algorithm(int[][,] population)
{
 
 
double[,] FitnessValue = new double[6, 2]; // for all five chromosome we store two Values the Fitness Value and the Fitness Ratio
 
int[] RouletteWheel = new int[6];
 
int round=0;
 
 
for (int geneticIteration = 0; geneticIteration < 10; geneticIteration++)
 
{
 
round = geneticIteration + 1;
 
writer = new StreamWriter("C:/Users/Welcome/Desktop/listOfChromosomesForAllRounds.txt", true);
 
writer.WriteLine("----------------------------------------------------------------------");
 
Chromosomes(population,round);
 
// Calculate the fitness Function and the Fitness Ratio
FitnessFunction(population); // Fitness Function
 
//RouletteWheel = RouletteWheel_Selection(population,FitnessValue); // Selection
 
//population = CrosssOver(RouletteWheel, population); //Cross Over
 
//population = Mutation(RouletteWheel, population); // Mutation
 
writer.Close();
 
 
}
 
//Store best path in the array as a group of XY coordinates
 
//for(int i=0;i<auvChromosomes.Length;i++)
 
//{
 
 
 
// }
 
//completeAUVMovement(int[,]auvPath);
 
}
"FitnessFunction" function :
public void FitnessFunction(int[][,] population)
{
 
double[,] FitnessValue = new double[6, 2]; // for all five chromosome we store two Values the Fitness Value and the Fitness Ratio
 
AUVbackGWgenetic = new BackgroundWorker();
 
AUVbackGWgenetic.DoWork += new DoWorkEventHandler (AUVbackGWgenetic_DoWork);
 
AUVbackGWgenetic.RunWorkerAsync(geneticIteration);
 
 
}
"AUVbackGWgenetic_DoWork" function :
private void AUVbackGWgenetic_DoWork(object sender, DoWorkEventArgs e)
{
 
 
Random rnd = new Random();
 
SoundPlayer player = new SoundPlayer("C:/Users/Welcome/Desktop/project/GAAPS/Sonar_pings.wav");
 
auv.auvX = rnd.Next(200, 325);
auv.auvY = rnd.Next(200, 325);
 
while (true)
{
 
Thread.Sleep(300); // assume that it represents the speed of the AUV which is in our case = 3 m/s
 
if (AUVbackGWgenetic.CancellationPending)
{
e.Cancel = true;
return;
}
 
 
if (auv.auvY == 200)
{
if (auv.queue1.Count != 0)
{
Thread.Sleep(1000);
 
foreach (Packet packet in auv.queue1)
{
auv.SendToSink(packet);
}
 
auv.queue1.Clear();
topology.CreateGraphics().DrawString("Received Aggrigated Data from AUV # " + auv.auvID, new Font("Times New Roman", 7.0f), Brushes.Red, sink.sinkX - 48, sink.sinkY - 15); // Display the sink name
topology.CreateGraphics().DrawLine(dash, auv.auvX, auv.auvY, sink.sinkX + 20, sink.sinkY + 45);
player.Play();
Thread.Sleep(3000);
player.Stop();
 
}
 
}
 
if (forward)
{
auv.auvX += 3;
 
auv.auvY += 3;
 
 
if (auv.auvY >= 326)
{
 
backward = true;
 
forward = false;
 
countNumOfPaths++;
 
}
 
}
 
if (backward)
{
 
auv.auvX -= 3;
 
auv.auvY -= 3;
 
if (auv.auvY >= 200)
{
 
backward = false;
 
forward = true;
 
countNumOfPaths++;
 
}
 
if (countNumOfPaths >= 2)
{
 
AUVbackGWgenetic.CancelAsync();
}
 
}
 
 
//////////////////////// Draw ///////////////////////////
 
iSetupDisplay = 0;
 
if (iSetupDisplay != -1)
{
iSetupDisplay += 10;
if (iSetupDisplay >= topology.Width)
iSetupDisplay = -1;
topology.Refresh();
}
 
/////////////////////////////////////////////////////////
 
}
 
 
}
What I have tried:
Run the background worker each time I call "FitnessFunction" function" which is responsible to stop it under a specific condition.
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

Related Links

Separate one process into several processes in C#
How to delete dynamically created textbox in asp.net
How to model relationship between multiple many to many object
Mock abstract protected method
How to add a looping selector to a Windows Phone 8.1 app?
AccessViolationException after copying a file from inside a zip archive to the clipboard and handling its data
How can I easily create a Func<T> from a method name?
C# Generic Passing different objects with same properties
Issue with Photometric Interpretation tag
Fixing possible memory leak in RelayCommand
Draw control like Google chrome
Expression tree creation with TryParse and Convert C#
Best way to keep a list in a wcf service memory
Gala type of game list of missile and list of asteroid collisions
MVC map Viewmodels to domain models
OpenGL transformations not working as expected

Categories

HOME
cryengine
artifactory
sugarcrm
ms-access-2010
aggregate-functions
opacity
travis-ci-cli
rtc
box-api
ndepend
suitecrm
dynamics-crm-2011
guidewire
multibinding
amazon-data-pipeline
google-calendar-api3
autologin
webgl-earth
lotusscript
angular2-pipe
procedural-generation
gulp-jshint
proof-general
resx
openoffice-impress
undo
multilanguage
mplab
spring-oauth2
pymunk
gstreamer-1.0
abide
mapquest
libconfig
var
motion
observer-pattern
mixed-models
flume-ng
logan-square
encoder
togglebutton
activeandroid
hierarchical-clustering
nao-robot
node-java
liferay-ide
multi-select
firebase-job-dispatcher
papyrus
xcode7.1
git-cherry-pick
sprockets
php-java-bridge
jsondoc
nslocalizedstring
yfiles
computability
updating
dnvm
roslyn-code-analysis
accpac
asp.net-2.0
attiny
backtrace
crtdbg.h
kss
mind-manager
indic
ios-enterprise
banana-pi
nodeunit
connections
boofcv
codio
lastinsertid
surfaceview
scidb
fade
nsnumber
uikit-dynamics
antixsslibrary
shapado
bindinglist
pdf-reader
nserror
mysql-connector
joomla1.7
nsundomanager
utm
visual-leak-detector
mismatch
hwnd
response-time
llblgen
versions
code-golf
uccapi
focus-stealing
user-preferences
unauthorized
urlscan

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App