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?
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] 삭제
몇 마디 만하겠습니다