Reputation: 35
I have a Windows form application which uses a start button to perform an infinite loop. I have a stop button which I am attempting to use to stop the infinite loop after the loop has completed a cycle.
I have attempted to use thread.Interrupt which doesn't allow the loop to finish.
I have also used thread.abort which obviously doesn't allow the loop to finish.
I have also attempted to do this by having the stop button update a global variable which the while loop inside my thread is reliant on but the global variable does not update inside the thread.
main class code
startbutton()
{
handle = getHandle();
Loopclass.loopclass loop = new Loopclass.loopclass(handle);
thread = new Thread(()=>loop.run());
thread.Start();
}
stopbutton()
{
handle = getHandle();
Loopclass.loopclass loop = new Loopclass.loopclass(handle);
loop.setCh();
}
Loop Class code
//_ch is a global string variable
Run()
{
while(_ch != "X")
{
//do stuff
string x = "";
_ch = getCh(x);
}
}
setCh()
{
_ch = "X";
}
getCh(string x)
{
x = "X";
return x;
}
Upvotes: 3
Views: 153
Reputation: 772
Use Task and CancellationToken:
private CancellationTokenSource tokenSource;
startbutton()
{
handle = getHandle();
Loopclass.loopclass loop = new Loopclass.loopclass(handle);
tokenSource = new CancellationTokenSource();
var task = Task.Run(() => loop.Run(tokenSource.Token));
}
stopbutton()
{
tokenSource.Cancel();
//handle = getHandle();
//Loopclass.loopclass loop = new Loopclass.loopclass(handle);
//loop.setCh();
}
Run(CancellationToken token)
{
while(!token.IsCancellationRequested && _ch != "X")
{
//do stuff
string x = "";
_ch = getCh(x);
}
}
setCh()
{
_ch = "X";
}
getCh(string x)
{
x = "X";
return x;
}
Upvotes: 3