C#.Rihter. How to stop thread work ? Cancellation token

how do i exit from thread

static void Main(string[] args)
{
    var tokenSource1 = new CancellationTokenSource();
    var token1 = tokenSource1.Token;
    
    var tokenSource2 = new CancellationTokenSource();
    var token2 = tokenSource2.Token;

    var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token1, token2);
    tokenSource1.Cancel();
    
    
    // adding actions on cancel
    token1.Register(() => Console.WriteLine("canceled1"));
    token1.Register(() => Console.WriteLine("canceled2"));
    
    ThreadPool.QueueUserWorkItem(o => ThreadWorker(token1, 1000));
    Console.WriteLine("Press <Enter> to cancel the operation.");
    Console.ReadLine();
    tokenSource1.Cancel();
}

private static void ThreadWorker(CancellationToken ct, Int32 count)
{
    for (int i = 0; i < count; i++)
    {
        if (ct.IsCancellationRequested) break;
        Thread.Sleep(1000);
        Console.WriteLine("hi from the thread the count is " + i);
    

Linked cancellation token – if any token will be canceled, linked token will be cancelled too

 var tokenSource1 = new CancellationTokenSource();
 var token1 = tokenSource1.Token;
 
 var tokenSource2 = new CancellationTokenSource();
 var token2 = tokenSource2.Token;

 var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token1, token2);
 tokenSource1.Cancel();

Cancellation token can also be created with timespan to cancel

public CancellationTokenSource(TimeSpan delay)

 

This entry was posted in Без рубрики. Bookmark the permalink.