using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine( "" );
CancellationTokenSource cts = new CancellationTokenSource( );
//ThreadPool.QueueUserWorkItem(CallBack, cts.Token );
ThreadPool.QueueUserWorkItem(CallBack, cts);
Console.WriteLine( "" );
Console.Read( );
cts.Cancel();
Console.ReadKey();
}
public static void CallBack( object state )
{
CancellationTokenSource cts = (CancellationTokenSource)state;
Console.WriteLine( "" );
Count( cts, 5 );
}
private static void Count(CancellationTokenSource cts, int countto )
{
for( int i=0; i<=countto+10; PPi) {
if( i== countto) {
cts.Cancel();
Console.WriteLine( "" );
//return;
}
Console.WriteLine( ":{0}, ID: {1}", i, Thread.CurrentThread.ManagedThreadId );
Thread.Sleep(300);
}
Console.WriteLine("");
}
}
}
it is obvious that the Count () function is still executing after calling cts.Cancel (). It is said in the book that CancellationTokenSource is a helper cancel thread. I just learned multithreading, and I don"t understand.
We put some tasks (functions) to be executed in a thread. If the task terminates, does it mean that the thread cancels
if the above code is changed to:
if( i== countto) {
cts.Cancel();
Console.WriteLine( "" );
return;
}
does this allow you to cancel the thread correctly.