问题描述
嗨!
如何中止已完成的任务。我使用了以下代码: -
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;
}
}
控件达到条件的时刻if(tasks [i] .Status == TaskStatus.RanToCompletion )它抛出错误对象引用未设置为对象的实例。任何人都可以告诉我这段代码有什么问题。
第二件事,我如何中止已完成的任务?
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?
推荐答案
if (tasks[i] != null &&
所以if的其余部分没有得到评估。
然后它到达第二个并试图测试实际上在什么任务[我] ......但是没有任何东西在那里它无法测试它。
so the rest of the if does not get evaluated.
Then it gets to the second one and tries to test what is actually in tasks[I]...but nothing is in there so it can't test it.
这篇关于中止完成任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!