1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CancellationTokenExperiments
{
    class CancellationTokenTest
    {
        static void Main(string[] args)
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            CancellationToken token = tokenSource.Token;
            tokenSource.Cancel();
            Task.Run(() => Console.WriteLine("Hello from Task"), token);

        }
    }
}

I am trying to understand the concept of cancellationTokens in C#. I understand that the above code will not print "Hello from Task" since the token is checked before the task is run.

However I have a couple of questions.

  1. Task.Run(() => Console.WriteLine("Hello from Task"), token);

What does the above statement mean? In the sense how it is different from simply calling Console.WriteLine("Hello from Task") ? Is it just that we are able to cancel the Task by passing the token? Also what does the empty braces () at the beginning of Task.Run mean?

  1. How do I change the above code so that I can stop the execution at a particular instance in time.
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
liv2hak
  • 14,472
  • 53
  • 157
  • 270
  • 1
    "Is it just that we are able to cancel the Task by passing the token" - No, the code in the task must inspect the cancellation token while it is running and exit if cancellation is requested. Tasks are not magically stopped just because there is a cancellation request. – Enigmativity Oct 10 '17 at 23:49
  • This is not really the same question as the one marked as a duplicate, even though they have the same title. The contents of the question and specific question being asked are different. – Samuel Neff Oct 11 '17 at 17:45

1 Answers1

-1

First, the empty braces is the syntax for a lambda expression with no parameters.

() => Console.WriteLine("Hello from Task")

Creates a function that is then passed to the task to run.

The value of cancellation comes in when you're managing multiple concurrent tasks (usually across threads). Reliable cross-thread synchronization and cancellation takes some work and understanding of multithreaded programming and using cancellation tokens vastly simplifies it and removes many common beginner pitfalls.

The token is used when you've started a longer running process in the background and then want to cancel it before it's done.

Samuel Neff
  • 73,278
  • 17
  • 138
  • 182
  • does `()` mean no parameter as in no parameter to the function ? It does take `string` as a parameter in the example. – liv2hak Oct 10 '17 at 23:46
  • @liv2hak - The `()` means that there are no parameters **passed in**. The call to `Console.WriteLine` has a parameter, but it wasn't **passed in**. – Enigmativity Oct 10 '17 at 23:47
  • @Samuel Neff - how do I modify the lambda to pass in the string? – liv2hak Oct 10 '17 at 23:50