取消引发的任务未设置对象引用 [英] Cancel a task raised Object reference not set
本文介绍了取消引发的任务未设置对象引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一段代码。
I have a piece of code.
class Program
{
static void Main(string[] args)
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
Task task = Task.Run(() =>
{
while (!token.IsCancellationRequested)
{
Console.Write('*');
Thread.Sleep(1000);
}
token.ThrowIfCancellationRequested();
}, token).ContinueWith((t)=>
{
t.Exception.Handle((e)=>true);
Console.WriteLine("You have canceled the task");
}, TaskContinuationOptions.OnlyOnCanceled); ;
try
{
Console.WriteLine("Press enter to stop the task");
Console.ReadLine();
cancellationTokenSource.Cancel();
task.Wait();
}
catch (AggregateException e)
{
Console.WriteLine(e.InnerExceptions[0].Message);
}
Console.WriteLine("Press enter to end the application");
Console.ReadLine();
}
}
当输入密钥时,我得到一个异常对象引用没有设置为对象的实例。我知道这是一个非常常见的简单和愚蠢的错误。
如果我删除task.Wait()那么错误就会消失但是无法弄清楚为什么。
I got an exception "Object reference not set to an instance of an object" when hit enter key. I know it is a very common simple and stupid error.
If I remove task.Wait() then the error will go away but just can't figure out why.
推荐答案
好的,弄清楚。
移动
Okay, figure it out.
Move
token.ThrowIfCancellationRequested();
到正确的位置。
to a proper position.
Task task = Task.Run(() =>
{
while (!token.IsCancellationRequested)
{
Console.Write('*');
Thread.Sleep(1000);
}
}, token).ContinueWith((t)=>
{
t.Exception.Handle((e)=>true);
Console.WriteLine("You have canceled the task");
}, TaskContinuationOptions.OnlyOnCanceled);
token.ThrowIfCancellationRequested();
try
{
Console.WriteLine("Press enter to stop the task");
Console.ReadLine();
cancellationTokenSource.Cancel();
//task.Wait();
}
catch (AggregateException e)
{
Console.WriteLine(e.InnerExceptions[0].Message);
}
Console.WriteLine("Press enter to end the application");
Console.ReadLine();
class Program
{
static void Main(string[] args)
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
Task task = Task.Run(() =>
{
while (true)
{
token.ThrowIfCancellationRequested();
Console.Write('*');
Thread.Sleep(1000);
}
}, token).
ContinueWith((t) =>
{
Console.WriteLine("You have canceled the task");
}, TaskContinuationOptions.OnlyOnCanceled);
try
{
Console.WriteLine("Press enter to stop the task");
Console.ReadLine();
cancellationTokenSource.Cancel();
}
catch (AggregateException e)
{
Console.WriteLine(e.InnerExceptions[0].Message);
}
task.Wait();
Console.WriteLine("Press enter to end the application");
Console.ReadLine();
}
}
这篇关于取消引发的任务未设置对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文