0
try{
      var cts = new CancellationTokenSource();
      CancellationToken ct = cts.Token;
      Task.Run(()=>
      {
          //DoSomething(); excute long time   
      }, ct);
      Task.Run(()=>
      {
          Thread.Sleep(1000);
          cts.Cancel();
      }, ct).Wait();
}
catch (OperationCanceledException ex)
{
      Console.WriteLine("exception" + ex.Message);
}
finally
{
      Console.WriteLine("finally");
}

When I call cts.Cancel()

DoSomething still Work.....................

how can i stop first Task?

if DoSomething Has a loop

I can add ct.ThrowIfCancellationRequested() , it's working

but DoSomething not a loop , what can i do ?

Jerry
  • 9
  • 5
  • I can't add IsCancellationRequested into Dosomething function have any way to Stop in Task not in Function(Dosomething)? – Jerry Sep 30 '17 at 09:08

1 Answers1

0

Whether or not DoSomething() is a loop, it must explicitly check and respond to the IsCancellationRequested property on the cancellation Token. If this property is true, the function must return as soon as practical, even if it means not completing the full execution. Note that DoSomething() is not a loop.

void DoSomething(System.Threading.CancellationToken tok)
{
    Thread.Sleep(900);
    if (tok.IsCancellationRequested)
        return;
    Console.WriteLine("after 1");
    Thread.Sleep(1800);
    if (tok.IsCancellationRequested)
        return;
    Console.WriteLine("after 2");

}
void Main()
{
    try
    {
        var cts = new CancellationTokenSource();
        CancellationToken ct = cts.Token;
        System.Threading.Tasks.Task.Run(() =>
        {
           DoSomething(ct);
          //DoSomething(); excute long time   
      });
        System.Threading.Tasks.Task.Run(() =>
        {
            Thread.Sleep(1000);
           cts.Cancel();
        }).Wait();
    }
    catch (OperationCanceledException ex)
    {
        Console.WriteLine("exception" + ex.Message);
    }
    finally
    {
        Console.WriteLine("finally");
    }
}

Note: DoSomething() must reference the cancellation token and explicitly check the IsCancellationRequested property. The role of the cancellation token in the Task.Run() is explained in this answer: https://stackoverflow.com/a/3713113/41410, but it doesn't play a role is cancelling the flow of DoSomething()

Phillip Ngan
  • 15,482
  • 8
  • 63
  • 79
  • i can't add IsCancellationRequested in Dosomething Function Have any way to stop it in Task not in Function(Dosomething)? – Jerry Sep 30 '17 at 08:46