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 handle in customauthorizeattribute an ajax request with antiforgerytoken
Authenticate with OneDrive SDK in a c# console project
Undefined symbols for architecture x86_64 “_main”
C# Black rectangle while focus by pressing tabulator key
ASP.NET Core MVC and EF Core 1.1
XMLDiff fails to recognize differences correcly?
Can a PrintDialog be modified?
Parse XML generated using C# Classes
How to take input in one line and separately store them in different variables
C# store contents from DB into list
Is it possible for Selenium to open an Excel Workbook pragmatically
MSAL. Detect revoked permissions and perform re-authorization
entity framework ado.net error SaveChanges()
Do I really need to clear a local list?
how to fill one jagged array from another one in c# [closed]
How to listen to events from a URI (C#)? [closed]

Categories

HOME
classification
youtube-api
javafx
leaflet
oracle-sqldeveloper
liquibase
gaussian
mifare
snmp
grid
webpack-dev-server
ephesoft
rtc
mamp
unreal-engine4
http-status-codes
drush
fastreport
opendaylight
infopath
loss
template10
project-reactor
draw2d
aiml
keystone
multipart
bootstrap-accordion
core-animation
jira-zephyr
grunt-contrib-uglify
symlink
libxml2
meteor-accounts
pushpad
ios9
urhosharp
epub
microstrategy
android-geofence
flex3
motherboard
kdevelop
rythm
scip
rtsp
yelp
nscollectionview
mybatis-generator
rbac
wicket-tester
ocpjp
jenkins-2
yank
beanshell
visio-2010
dotnet-cli
dynamic-linking
intermediate-language
openpgp.js
boost-regex
printer-control-language
codesniffer
timex
therubyracer
copy-constructor
android-music-player
symantec
cherry-pick
db2-zos
sbt-proguard
shtml
3d-rendering
usps
window.location
treelist
dcast
oryx
windows-kernel
edgar
exchange-server-2007
p4python
maven-archetype
xmla
alpha-beta-pruning
jsonmodel
system.net
parsefloat
dotcmis
webshim
jsmpp
pidgin
git-subtree
kernel-density
android-jack-and-jill
node-amqp
facebook-likebox
ekevent
octokit
nokogiri
mmo
microsoft-speech-platform
screensharing
volatility
jquery-ui-map
umfpack
opendir
excellibrary
llblgen
browser-state
qprocess
newspeak
mysql-pconnect
focus-stealing
coderush-xpress
expander

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