Task.ContinueWith doesn't work after previous Task completed

Maxim Zhukov

While i read Jeffrey Richter, CLR via C#, i've found this example. There are expected executing new Tasks depending on TaskContinuationOptions, but it isn't. I thought i would have next result:

Finished, SUM=5050

but i have empty output, even if i add throw exception in Sum function, OnlyOnFaulted wouldn't be executed.

class Program
{
    public static Int32 Sum(Int32 n)
    {
        Int32 Sum = 0;
        for (; n > 0; n--)
            Sum += n;

        return Sum;
    }

    static void Main(string[] args)
    {
        Task<Int32> t = new Task<Int32>(n => Sum((Int32)n), 100);

        t.ContinueWith(tt => Console.WriteLine("Finished, SUM={0}", tt.Result), TaskContinuationOptions.OnlyOnRanToCompletion);
        t.ContinueWith(tt => Console.WriteLine("Exception thrown"), TaskContinuationOptions.OnlyOnFaulted);

        t.Start();            
    }
}

What i'm doing wrong?

Sergey Berezovskiy

Actually you setup continuation correctly, but you can't see result on console, because application exists before:

Task<Int32> t = new Task<Int32>(n => Sum((Int32)n), 100);

t.ContinueWith(tt => Console.WriteLine("Finished, SUM={0}", tt.Result),
               TaskContinuationOptions.OnlyOnRanToCompletion);
t.ContinueWith(tt => Console.WriteLine("Exception thrown"), 
               TaskContinuationOptions.OnlyOnFaulted);

t.Start();
Console.ReadKey(); // keep app alive

Application will not wait for background thread completion - it will be closed when main thread of application finishes it's work (your Main method)

편집 또 다른 옵션은 백 라운드 스레드 (연속 스레드)가 완료 될 때까지 대기하고 응용 프로그램을 활성 상태로 유지하는 것입니다.

Task continuation = 
    t.ContinueWith(tt => Console.WriteLine("Finished, SUM={0}", tt.Result),
                   TaskContinuationOptions.OnlyOnRanToCompletion);

t.Start();
continuation.Wait(); // wait until continuation of task finishes
// exit application

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Task scheduler doesn't work unless I run it manually

분류에서Dev

Redirect to previous URL after login/register doesn't work

분류에서Dev

Task. ContinueWith Chain Sequence of Events

분류에서Dev

Repeat a task (TPL) in windows service, using ContinueWith

분류에서Dev

ColorAnimation, Completed event doesn't work more then once

분류에서Dev

How to handle different Task exceptions with Wait() of parent and child.ContinueWith?

분류에서Dev

NotOnRanToCompletion Continuation doesn't run when parent task is cancelled

분류에서Dev

Bat file doesn't log when running from task scheduler?

분류에서Dev

이전 Task.Result에 종속 된 C # Task.continuewith

분류에서Dev

After mapster href doesn't work

분류에서Dev

SetValue method doesn't work after DoubleAnimation

분류에서Dev

toggleClass() doesn't work after first time

분류에서Dev

How to cancel previous Task if new request recieved?

분류에서Dev

Task <T>의 ContinueWith 메서드를 호출 (직접 호출하지 않음)하는 방법은 무엇입니까?

분류에서Dev

task scheduler after 5 min

분류에서Dev

Let user start celery task, and let user know when task is completed

분류에서Dev

C++/CLI code doesn't enter .then part of the create_task function

분류에서Dev

VM doesn't work anymore after umount an lv

분류에서Dev

ubuntu 12.4, wireless doesn't work after update

분류에서Dev

suspend doesn't work after upgrading to Debian 7.8

분류에서Dev

Rotate animation after Translate doesn't work on Android

분류에서Dev

Task <T>에서 T 검색

분류에서Dev

Suspend a running task then resume it AFTER a system restart

분류에서Dev

JBPM Workflow not moving forward after Human Task

분류에서Dev

Task.ContinueWith를 할당하는 올바른 형식은 무엇입니까?

분류에서Dev

Task <T> 시작 연기

분류에서Dev

unbind doesn't work

분류에서Dev

Crontab doesn't work

분류에서Dev

How to make code work - USACO Training First Task

Related 관련 기사

  1. 1

    Task scheduler doesn't work unless I run it manually

  2. 2

    Redirect to previous URL after login/register doesn't work

  3. 3

    Task. ContinueWith Chain Sequence of Events

  4. 4

    Repeat a task (TPL) in windows service, using ContinueWith

  5. 5

    ColorAnimation, Completed event doesn't work more then once

  6. 6

    How to handle different Task exceptions with Wait() of parent and child.ContinueWith?

  7. 7

    NotOnRanToCompletion Continuation doesn't run when parent task is cancelled

  8. 8

    Bat file doesn't log when running from task scheduler?

  9. 9

    이전 Task.Result에 종속 된 C # Task.continuewith

  10. 10

    After mapster href doesn't work

  11. 11

    SetValue method doesn't work after DoubleAnimation

  12. 12

    toggleClass() doesn't work after first time

  13. 13

    How to cancel previous Task if new request recieved?

  14. 14

    Task <T>의 ContinueWith 메서드를 호출 (직접 호출하지 않음)하는 방법은 무엇입니까?

  15. 15

    task scheduler after 5 min

  16. 16

    Let user start celery task, and let user know when task is completed

  17. 17

    C++/CLI code doesn't enter .then part of the create_task function

  18. 18

    VM doesn't work anymore after umount an lv

  19. 19

    ubuntu 12.4, wireless doesn't work after update

  20. 20

    suspend doesn't work after upgrading to Debian 7.8

  21. 21

    Rotate animation after Translate doesn't work on Android

  22. 22

    Task <T>에서 T 검색

  23. 23

    Suspend a running task then resume it AFTER a system restart

  24. 24

    JBPM Workflow not moving forward after Human Task

  25. 25

    Task.ContinueWith를 할당하는 올바른 형식은 무엇입니까?

  26. 26

    Task <T> 시작 연기

  27. 27

    unbind doesn't work

  28. 28

    Crontab doesn't work

  29. 29

    How to make code work - USACO Training First Task

뜨겁다태그

보관