我尝试在取消下面的任务时运行一个简单的例子
CancellationTokenSource tokenSource2 = new CancellationTokenSource();
CancellationToken token2 = tokenSource2.Token;
Task task2 = new Task(() =>
{
for (int i = 0; i < int.MaxValue; i++)
{
token2.ThrowIfCancellationRequested();
Thread.Sleep(100);
Console.WriteLine("Task 2 - Int value {0}", i);
}
}, token2);
task2.Start();
Console.WriteLine("Press any key to cancel the task");
Console.ReadLine();
tokenSource2.Cancel();
Console.WriteLine("Task 2 cancelled? {0}", task2.IsCanceled);
Run Code Online (Sandbox Code Playgroud)
我预计 Console.WriteLine("Task 2 cancelled? {0}", task2.IsCanceled);会打印**"Task 2 cancelled? True"**,但它打印"假".
你知道发生了什么吗?这是预期的行为吗?谢谢.
编辑:确保在调用取消请求之前未完成任务.我加了Console.ReadLine().
当我取消任务时,等待结果仍然为IsCanceled属性返回true.似乎有些事情出了问题.
请指教.这是代码:
CancellationTokenSource _cancelLationToken = new CancellationTokenSource();
private async void Button_Click(object sender, EventArgs e)
{
_cancelLationToken = new CancellationTokenSource();
_cancelLationToken.Token.Register(theCallBack);
var myTaskToWaitFor = Task.Factory.StartNew(() => WorkHard(_cancelLationToken.Token), _cancelLationToken.Token);
await myTaskToWaitFor;
int i=0;
if(myTaskToWaitFor.IsCanceled)
i = i; //breakpoint for debugging
else
i = i; //breakpoint for debugging <== always ends here... :-(
}
private void WorkHard(CancellationToken token)
{
for(int i = 0; i < 100000000; i++)
if(token.IsCancellationRequested)
break;
else
Math.Acos(Math.Pow(i, i / 10000000));
}
public void theCallBack()
{
//todo: do something
} …Run Code Online (Sandbox Code Playgroud) 我有以下示例代码:
static class Program
{
static void Main()
{
var cts = new CancellationTokenSource();
var task = Task.Factory.StartNew(
() =>
{
try
{
Console.WriteLine("Task: Running");
Thread.Sleep(5000);
Console.WriteLine("Task: ThrowIfCancellationRequested");
cts.Token.ThrowIfCancellationRequested();
Thread.Sleep(2000);
Console.WriteLine("Task: Completed");
}
catch (Exception exception)
{
Console.WriteLine("Task: " + exception.GetType().Name);
throw;
}
}).ContinueWith(t => Console.WriteLine("ContinueWith: cts.IsCancellationRequested = {0}, task.IsCanceled = {1}, task.Exception = {2}", cts.IsCancellationRequested, t.IsCanceled, t.Exception == null ? "null" : t.Exception.GetType().Name));
Thread.Sleep(1000);
Console.WriteLine("Main: Cancel");
cts.Cancel();
try
{
Console.WriteLine("Main: Wait");
task.Wait();
}
catch (Exception exception)
{
Console.WriteLine("Main: Catch …Run Code Online (Sandbox Code Playgroud)