How to cancel a Task using CancellationToken?

Netherstorm

So I've this code:

//CancelationToken
CancellationTokenSource src = new CancellationTokenSource();
CancellationToken ct = src.Token;
ct.Register(() => Console.WriteLine("Abbruch des Tasks"));
//Task
Task t = new Task(() =>
{
    System.Threading.Thread.Sleep(1000);
    if (ct.IsCancellationRequested)
    {
        try
        {
            //Throw
            ct.ThrowIfCancellationRequested();                        
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine(
                "ThrowIfCancellationRequested() liefert eben eine Exception");
        }
    }             

}, ct);
//Run Task and Cancel
t.Start();
src.CancelAfter(350);
t.Wait();

// Get Information
Console.WriteLine("Canceled: {0} . Finished: {1} . Error: {2}",
                    t.IsCanceled, t.IsCompleted, t.IsFaulted);

So in this case I canceled my Task but my output in the end is: "Canceled: False . Finished: True . Error: False"

In my opinion it should be "Canceled:True . Finished:False". Why do I get this result? Because I try to catch the exception?

I've tried it without the try - catch block, but then my program stops because of the OperationCanceledException. Can somebody help me?

Yuval Itzchakov

You're swallowing the exception, thus the task is flagged as finished as you actually handle the exception and it doesn't propagate outwards.

Instead, don't catch the exception inside the delegate, catch it outside:

void Main()
{
    CancellationTokenSource src = new CancellationTokenSource();
    CancellationToken ct = src.Token;
    ct.Register(() => Console.WriteLine("Abbruch des Tasks"));

    Task t = Task.Run(() =>
    {
        System.Threading.Thread.Sleep(1000);
        ct.ThrowIfCancellationRequested();
    }, ct);

    src.Cancel();
    try
    {
        t.Wait();
    }
    catch (AggregateException e)
    {
        // Don't actually use an empty catch clause, this is
        // for the sake of demonstration.
    }

    Console.WriteLine("Canceled: {0} . Finished: {1} . Error: {2}",
                       t.IsCanceled, t.IsCompleted, t.IsFaulted);
}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Using a CancellationToken to cancel a task without explicitly checking within the task?

分類Dev

How to get effect of Task.WhenAny for a Task and CancellationToken?

分類Dev

C#でTask.delayのcancellationToken.cancelを処理する方法は?

分類Dev

How do I cancel third party task?

分類Dev

How to cancel previous Task if new request recieved?

分類Dev

How to cancel a TaskCompletionSource using a timout

分類Dev

Cancel Task in async void

分類Dev

How to pass CancellationToken to WebApi action?

分類Dev

Cancel a loop in a task from outside

分類Dev

When does Task.Run(Action, CancellationToken) throw TaskCanceledException?

分類Dev

Dispose of ControllerでcancellationToken.Cancel()を呼び出していますか?

分類Dev

Task.WhenAny for a Task and CancellationTokenの効果を得る方法は?

分類Dev

How to set periodic task on Django using celery?

分類Dev

How to cancel UserNotifications

分類Dev

How to cancel a request properly?

分類Dev

How to cancel the toast in android?

分類Dev

Task.RunSynchronously()はCancellationTokenを気にしません

分類Dev

Does Future.cancel(true) remove the task from the queue?

分類Dev

Cancel specific child thread or task after unsubscribing socket stream

分類Dev

How to schedule a periodic task that is immune to system time change using Python

分類Dev

How to show the time when task was created by using react

分類Dev

how to print task name using taskId in Laravel 5.2

分類Dev

How to cancel the query sent by MediatR?

分類Dev

How to cancel delay in telnet connection?

分類Dev

task.Wait(CancellationToken)をawaitステートメントに変換する方法は?

分類Dev

Cancel goroutines on first error using errgroup

分類Dev

MapReduce task using channels

分類Dev

Using copy task with unzip task in msbuild

分類Dev

Swift: searchBar - how to change "Cancel" Button title

Related 関連記事

  1. 1

    Using a CancellationToken to cancel a task without explicitly checking within the task?

  2. 2

    How to get effect of Task.WhenAny for a Task and CancellationToken?

  3. 3

    C#でTask.delayのcancellationToken.cancelを処理する方法は?

  4. 4

    How do I cancel third party task?

  5. 5

    How to cancel previous Task if new request recieved?

  6. 6

    How to cancel a TaskCompletionSource using a timout

  7. 7

    Cancel Task in async void

  8. 8

    How to pass CancellationToken to WebApi action?

  9. 9

    Cancel a loop in a task from outside

  10. 10

    When does Task.Run(Action, CancellationToken) throw TaskCanceledException?

  11. 11

    Dispose of ControllerでcancellationToken.Cancel()を呼び出していますか?

  12. 12

    Task.WhenAny for a Task and CancellationTokenの効果を得る方法は?

  13. 13

    How to set periodic task on Django using celery?

  14. 14

    How to cancel UserNotifications

  15. 15

    How to cancel a request properly?

  16. 16

    How to cancel the toast in android?

  17. 17

    Task.RunSynchronously()はCancellationTokenを気にしません

  18. 18

    Does Future.cancel(true) remove the task from the queue?

  19. 19

    Cancel specific child thread or task after unsubscribing socket stream

  20. 20

    How to schedule a periodic task that is immune to system time change using Python

  21. 21

    How to show the time when task was created by using react

  22. 22

    how to print task name using taskId in Laravel 5.2

  23. 23

    How to cancel the query sent by MediatR?

  24. 24

    How to cancel delay in telnet connection?

  25. 25

    task.Wait(CancellationToken)をawaitステートメントに変換する方法は?

  26. 26

    Cancel goroutines on first error using errgroup

  27. 27

    MapReduce task using channels

  28. 28

    Using copy task with unzip task in msbuild

  29. 29

    Swift: searchBar - how to change "Cancel" Button title

ホットタグ

アーカイブ