I have code like below. Simply run the while loop for a long time.
public void Test(){
var task1 = Task.Run(() =>
{
while(true){
// forever
}
}
}
When Test() is called, task1 will be executed. Then, when I run Test() again immediately, two tasks exist at the same time.
Is there a way to cancel the task that was already running when a new task is created?
Edit for Michał Turczyn
int i = 0;
private CancellationTokenSource cancellationTokenSource;
public void Test(int b)
{
if (cancellationTokenSource != null)
{
// Cancel previously created task.
cancellationTokenSource.Cancel();
}
cancellationTokenSource = new CancellationTokenSource();
var task1 = Task.Run(() =>
{
while (!cancellationTokenSource.IsCancellationRequested)
{
Console.WriteLine(b);
// forever
}
});
}
public void button_pushed(){
Console.WriteLine("pushed");
Test(i); i++; return;
}
The log is like:
pushed
0
0
0
0
0
pushed
1
1
1
1
pushed
1
1
1
1
2
2
2
2
2
1
1
1
1
2
2
2
pushed
1
1
1
1
2
2
2
2
2
1
1
1
1
3
3
3
3
2
2
2
....
It looks like past tasks are still running. But when I executed it three times, the first output (0) disappeared, so is this a timing issue?
What I looking for is like:
pushed
0
0
0
0
pushed
1
1
1
1
pushed
2
2
2
2
....
task1as a field / property instead of local variable?CancellationTokento the method., then change towhile (!CancellationToken.IsCancelationRequested).BackgroundService?// foreverrepresents some code that you want to run periodically. It is important to clarify what do you want to happen when thebutton_pushedevent occurs. Do you want 1. To wait peacefully for the completion of the// forevercode before launching the new task or 2. Abort/kill/terminate immediately and forcefully the// forevercode and then launch the new task?