Intro To begin with, I have already read the following articles and to my opinion they do not answer this question:
Cancellation token in Task constructor: why? What is the use of passing CancellationToken to Task Class constructor?
It's clear to me what the use is of the token parameter.
My question I tried to document the code with inline comments to give you an idea of where I'm missing how this all chains together.
The code does what I want it to do: - Write to the console every 2 seconds - Stop after 10 seconds
My question: how does the "howDoIGetFilled" parameter get the value of the "token" parameter. The second parameter is for the Task instance itself, not the Action being used. If anything isn't clear, please let me know what you want clarified.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TaskDelegatePlayground
{
class Program
{
static void Main(string[] args)
{
var source = new CancellationTokenSource();
var token = source.Token;
Action<object> action = howDoIGetFilled => TestCancellationWithToken((CancellationToken)howDoIGetFilled);
//I understand that this works, as you pass in the token and it gets passed to the "howDoIGetFilled" variable.
//action(token);
//Wrong because it's "hardcoding" the token variable now but I don't understand how the above gets filled in.
//Action<object> action = howDoIGetFilled => TestCancellationWithToken(token);
var task = new Task(action, token);
task.Start();
Thread.Sleep(10000);
//This should cancel the operation
Console.WriteLine("Cancelling");
source.Cancel();
Console.WriteLine("Ended, press any key to close the application.");
Console.ReadKey();
}
public static void TestCancellationWithToken(CancellationToken token)
{
//no intellisense here for token / source
while (true)
{
if (token.IsCancellationRequested)
break;
Console.WriteLine("test");
Thread.Sleep(2000);
}
}
}
}