Is there a way to fetch currently running task by ID once you get out of the method where you initially started the task? I would like to get somehow current tasks so I can stop some of them mid-execution without interrupting the flow of the program.
For example:
class Test
{
List<Task> listOfTasks = new List<Task>();
void taskCaller()
{
try
{
var myTask = Task.Factory.StartNew(()=> testMethod());
listOfTasks.Add(myTask);
}
catch (System.Exception)
{
//...
throw;
}
}
void taskGetter()
{
foreach (var item in listOfTasks)
{
if(item == something)
{
item.KillExecution();
}
}
}
private void testMethod()
{
// doing something
throw new NotImplementedException();
}
}
EDIT
I want it done without cancellation tokens if possible as it doesn't work for me as I want it to because I am running a timer fetching DLL from DB and cancellation tokens work only if I immediately kill the task with token.Cancel()
however if I try token.CancelAfter()
it doesn't work because it gets triggered only after the task finished with the execution, which kind of isn't the idea.
EDIT2:
Not to copy tons of code, here is the pseudo of the whole flow:
new timer(repeat method every xx time units)
open DB
do some work
save DB
Continuing with plast1k suggestion...
When I check the dictionary if the cancellation is requested in this scenario, it says true
but it doesn't do anything to the running task
private void getActiveTasks()
{
if (!ListOfTasks.Any())
return;
Console.WriteLine("Currently running:");
foreach (var task in ListOfTasks)
{
Console.WriteLine("\t" + task.Key);
Console.WriteLine("\t" + task.Value.MyTask.Id);
task.Value.Token.Cancel();
Console.WriteLine("\t" + task.Value.Token.IsCancellationRequested);
ListOfTasks.Remove(task.Key);
return;
}
}