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

Export only grid view data on excel from page through C#
'Conversion failed' error is not captured while executing in C# or in stored procedure
c# async await and exception
Generic caching in c#
Parse - Resetting Passwords on ASP.NET MVC
Not all code paths return a value for boolean method in class
Unit of work and general repository package
Getting version number from a running proccess ( With NO access to the .exe path)
How do I pass selectlist that is string to controller to save as a int value in asp.net mvc 5
WPF binding/display of different units
Unity - ensure that only one instance does the given command
Entity Framework Migrations not creating tables on database publishing
JSON format C# not generating all quotes the serializer
UWP: how to customize the app title
Crystal report SetParameterValue
Connecting Sphero & a Windows UWP app

Categories

HOME
redux
highmaps
coordinates
kendo-asp.net-mvc
pip
ionic-native
osrm
adroitlogic
guidewire
javascript-debugger
repeater
hql
sha1
facebook-marketing-api
android-actionbar
wallet
civicrm
caldav
bug-reporting
monad-transformers
dev-c++
policy
apdu
android-cursorloader
pypy
ds-5
undo
language-detection
visual-prolog
bootcamp
minitest
android-geofence
pygraphviz
sknode
irr
anonymous-function
openxava
ear
jtextarea
trusted-computing
iban
optional-parameters
indoor-positioning-system
dbi
virtualenvwrapper
scriptengine
instaparse
vitamio
supervised-learning
camellia
treelist
salesforce-service-cloud
wizard
datamodel
dday
clear
dynamics-nav
commercetools
windows-kernel
javapackager
jts
cloud-storage
android-filterable
tinymce-plugins
valdr-bean-validation
parseexception
chrome-mobile
report-builder2.0
jsonschema2pojo
go-gin
redmine-plugins
powershell-v1.0
drawable
episerver-7
sendy
jsmpp
azure-caching
class-library
git-subtree
autofilter
google-mirror-api
google-voice
fade
azure-pack
kademlia
latex-suite
gpl
django-tinymce
nsregularexpression
jquery-ui-map
github-archive
bindinglist
django-admin-tools
helicontech
yii-cactiverecord
lightopenid
zipstream
meego-harmattan
cryptolicensing
javah
mass-emails
text-manipulation
silverlight-2.0
uccapi
lts
djangoappengine
onresize
cross-cutting-concerns

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