I have a method called StartAutomation
that executes a block of code inside a Task.Factory.StartNew(() => { });
to not block the UI while working on heavy loads. All is well until I started working on a way to cancel/abort a running Task at any point of time the user wishes to. I then followed this discussion on how I can abort a running Task and, for all that its worth, it works. It does cancel the running task with not errors and whatnot which I contained inside a separate method I then called StopAutomation
.
However, after calling StopAutomation
and deciding to give it another run by calling StartAutomation
once more, the code inside Task.Factory.StartNew(() => { });
does not produce any result.
Below is my code snippet:
private Thread automationThread;
public void StartAutomation()
{
Task.Factory.StartNew(() =>
{
automationThread = Thread.CurrentThread;
try
{
Console.WriteLine("Starting process...");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
});
}
public void StopAutomation()
{
Console.WriteLine("Stopping...");
automationThread.Abort();
}
Scenario:
- User presses a button that calls
StartAutomation()
, code executes and a text is written on the screen. - User decides to cancel ongoing task. So they press a button that calls
StopAutomation()
- After a certain amount of time, User pressed the button that calls
StartAutomation()
again. The code no longer executes and no text is written on the screen.