In the previous blog exploring the cancellation Task _c # _ Huangteng Xiao's blog -CSDN blog describes task.run need to take the initiative to call during execution method ThrowIfCancellationRequested () to cancel, this time we study other cases of cancellation scene
Task .Delay
We know that Task.Dealy
there is a heavy load can be passed CancellationToken
, we make the following experiment
static void Main(string[] args)
{
var source = new CancellationTokenSource();
Foo(source.Token);
Thread.Sleep(TimeSpan.FromSeconds(3));
source.Cancel();
Console.WriteLine("取消任务");
Console.ReadLine();
}
public static void Foo(CancellationToken token)
{
Task.Delay(TimeSpan.FromSeconds(5), token)
.ContinueWith(task => Console.WriteLine(task.Status));
}
And similar experiments before, only Task.Run
replaced Task.Delay
. The results shown in FIG.
Visible Task.Delay
direct response canceled
Parallel
Again we Parallel
do experiments
static void Main(string[] args)
{
var source = new CancellationTokenSource();
Foo(source.Token);
Thread.Sleep(TimeSpan.FromSeconds(3));
source.Cancel();
Console.WriteLine("取消任务");
Console.ReadLine();
}
public static void Foo(CancellationToken token)
{
var options = new ParallelOptions()
{
CancellationToken = token,
};
Task.Run(() =>
{
Parallel.For(0, 10, options, (i, state) =>
{
Console.WriteLine($"{i}任务开始");
Thread.Sleep(TimeSpan.FromSeconds(5));
Console.WriteLine($"{i}任务结束");
});
});
}
By Parallel.For
create 10 parallel tasks, each task takes 5 seconds to cancel the task for the first three seconds. The results shown in FIG.
Visible Parallel.For
behavior and Task.Run
is consistent
Reference links:
-
Task explore cancellation _c # _ Huangteng Xiao's blog -CSDN blog
-
How to: Use Parallel.Invoke to Execute Parallel Operations - Microsoft Docs
This article will be updated frequently, please read personal blog Original: https://xinyuehtx.github.io/ , in order to avoid misleading the old error of knowledge, and a better reading experience.
This work is Creative Commons Attribution - NonCommercial - ShareAlike 4.0 International License Agreement for licensing. Welcome to reprint, use, repost, but be sure to keep the article signed by Huang Tengxiao (containing links: https://xinyuehtx.github.io/ ), shall not be used for commercial purposes, be sure to publish the same work based on the paper license modification. If you have any questions, please contact me .