Reputation: 166
I would like to know if there is a way to dynamically change the parameters passed to a method when it running in a thread.
For example:
trdColCycl thread = new Thread (() => this.ColorsCycling (true));
trdColCycl.Start();
or
trdColCycl thread = new Thread (new ParameterizedThreadStart (this.ColorsCycling));
trdColCycl.Start(true);
and then I want to pass as a parameter to the thread running the value false
... is it possible?
(in this example I would like to dynamically change the parameter value to exit from a loop inside the thread without using global variables)
Thanks for your help.
Upvotes: 1
Views: 1557
Reputation: 6122
You could create a shared variable meant for communicating between two threads
class ArgumentObject
{
public bool isOk;
}
// later
thread1Argument = new ArgumentObject() { isOk = true };
TrdColCycl thread = new Thread (() => this.ColorsCycling (thread1Argument));
trdColCycl.Start();
// much later
thread1Argument.isOk = false;
Alternatively, you could pass the bool as reference instead:
bool isOk = true;
TrdColCycl thread = new Thread (() => this.ColorsCycling (ref isOk));
trdColCycl.Start();
// later
isOk = false;
In both cases, you'll have to modify the signature of your method:
// original
void ColorsCycling(bool isOk)
// should be
void ColorsCycling(ArgumentObject argument) // for option 1
// or
void ColorsCycling(ref bool isOk) // for option 2
Upvotes: 2