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

How to write a generic ISort interface?
Comparing Sum Methods in C#
Pass Linq Expression to a function
nHibernate stored procedure call
Invalid authorization specification and Invalid connection string attribute
How to bind list inside a list to a GridView in ASP.NET
How can I use a client certificate with a missing CA to communicate with a external Web service?
Registering and using forms with Windsor
Fast serialization/deserialization of structs
Sending UTF-8 Text Messages on C# using TIBCO EMS
Strategy, State, Singleton… or a Composition thereof?
Handling the events of a Interop control in C#
Regex to capture text around a literal
Why my TempData is not working
Fetching information from a database
data type mismatch in criteria expression in c# 2010

Categories

HOME
actionscript-3
drupal
gsm
gap-system
latex
data-modeling
cryengine
crm
singleton
coordinates
confluence-rest-api
vsixmanifest
token
ethereum
distinct
ng2-charts
mbed
minimum
box2d
greensock
openscad
pylint
windows-phone
sonarlint
datasource
serenity-js
ng-tags-input
aws-iot
concatenation
chartist.js
grunt-contrib-uglify
nsopenpanel
akavache
spock
jmsserializerbundle
wercker
rtos
sampling
dom4j
respect-validation
rythm
kepserverex
dotnetnuke-module
nscollectionview
mediastream
ssdp
file-descriptor
irr
datagridviewcombobox
denodo
r-commander
programming-pearls
blackberry
lightspeed
google-scholar
blitz3d
gevent
optional-parameters
firebase-polymer
mac-app-store
eclipse-mars
dbi
jspx
geokit
instaparse
hoare-logic
qtruby
jcalendar
dcast
nslocalizedstring
windows-kernel
exchange-server-2007
hexagonal-tiles
dpkt
dcg
applinks
javadb
famous-engine
livescript
ant-contrib
rda
smartxls
android-jack-and-jill
php-amqplib
facebook-likebox
google-mirror-api
infomaker
source-depot
kademlia
uikit-dynamics
http-compression
ftpwebrequest
quit
orchestration
nsscrollview
win-prolog
unordered-set
visual-leak-detector
apache-commons-email
virtual-destructor
qprocess
lts
script-tag
user-preferences
ffdshow
office-2003

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