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

Updating secondary tiles with images in Windows 10 app
Windows8 backgroundtask with async tasks (deferral)
Date Format in C# Linq
Determine if all elements of a List are true or false [duplicate]
asp-net Telerik grid not getting populated
Serilog LogContext vs Enrich in Owin
*.dll.licenses file in obj directory not created with msbuild in TeamCity
[WP 8.1]Error when validating the app to store
How to assign JsonProperty attribute to properties of classes inside DLL using Json.Net?
How to display Images from One Project to Another Project using ASP.Net?
How to put editable text in static text paragraph in WPF
Get a MenuItem to switch to a different visible window when clicked
System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.WindowsAzure.ServiceRuntime, Version=2.5.0.0
How to consume Odata service method in c# or in jquery
Trigger an API from Background Task at a Fixed time
Duplicate assembly embedding

Categories

HOME
netty
system-calls
jenkins-pipeline
display
azure-eventhub
skypedeveloper
x509certificate
lithium
css-selectors
richtextbox
opacity
restheart
digital
opendaylight
web-parts
wallet
gpo
xforms
bug-reporting
oracle-golden-gate
uipath
datastax-enterprise
suitescript
scalatest
sasl
cloudformation
sqldependency
spock
javapns
mobile-development
jql
keil
wercker
storefront
webspeech-api
minitest
ansible-inventory
hippocms
outlook-2010
nsdateformatter
julia-jump
vertical-alignment
jvisualvm
pyexcel
quartz
vpython
rexx
api-key
logan-square
encoder
enet
playframework-1.x
seyren
scrollmagic
esprima
stringbuilder
directinput
scikit-image
visual-web-developer
git-cherry-pick
mrunit
3d-rendering
containstable
dynamics-nav-2013
tvp
jain-sip
properties-file
sparkcore
eula
genome
skview
conkeror
qxorm
information-hiding
growl
nsurlrequest
yosemite
parsefloat
dateadd
image-preloader
acrofields
mixradio
starling-framework
grunt-wiredep
svg-android
pechkin
nokogiri
kohana-orm
angularjs-select2
asp.net-4.0
dd4t
select2-rails
junction-table
nsautoreleasepool
django-tinymce
quit
php-gettext
visual-leak-detector
xhtmlrenderer
noise-reduction
html5-animation
chromebug
jquery-attributes
mysql-pconnect
ihtmldocument2
ffdshow

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App