Harsh Jani

Harsh Jani

  • NA
  • 34
  • 52k

How to Abort completed tasks

Apr 10 2015 12:56 AM
Hi!
How do I abort completed tasks. I have used the following code: -
class Program
{
static void Main(string[] args)
{
System.Timers.Timer myTimer = new System.Timers.Timer();
myTimer.Elapsed += new ElapsedEventHandler(OnTimer);
myTimer.Interval = 1000;
myTimer.Enabled = true;
myTimer.AutoReset = false;
Console.WriteLine(@"Press 'q' and 'Enter' to quit...");
while (Console.Read() != 'q')
{
Thread.Sleep(1000);
}
}
public static void OnTimer(Object source, ElapsedEventArgs e)
{
System.Threading.Tasks.Task[] tasks = new System.Threading.Tasks.Task[10];
for(int i=0; i<10; i++)
{
if (tasks[i] != null && (tasks[i].Status == TaskStatus.Running || tasks[i].Status == TaskStatus.WaitingToRun || tasks[i].Status == TaskStatus.WaitingForActivation))
{
Console.WriteLine("Task has attempted to start while already running");
}
else
{
Console.WriteLine("Task {0} has begun", i);
Thread.Sleep(1000);
}
if (tasks[i].Status == TaskStatus.RanToCompletion)
{
Console.WriteLine("\n\n\t");
Console.WriteLine("Task{0} has completed", i);
}
}
Console.WriteLine();
Console.WriteLine();
System.Timers.Timer theTimer = (System.Timers.Timer)source;
theTimer.Interval += 1000;
theTimer.Enabled = true;
}
}
The moment the control reaches on the condition if(tasks[i].Status == TaskStatus.RanToCompletion) it throws an error "Object reference not set to an instance of an object". Can anyone tell me what's wrong with this code.
Second thing, how do i abort the completed tasks?

Answers (1)