継続タスク途中で未補足な例外が発生しても後続のタスクは実行される。
public static class ContinueWithExample
{
public static void Run()
{
var task = Task.Factory.StartNew(() =>
{
Thread.Sleep(500);
throw new Exception("なんらかのエラー");
})
.ContinueWith((t) =>
{
//実行される
Console.WriteLine("IsFaulted:{0}", t.IsFaulted); //True
Thread.Sleep(500);
//throw new Exception("なんらかのエラー2");
})
.ContinueWith((t2) =>
{
//実行される
Console.WriteLine("IsFaulted:{0}", t2.IsFaulted); //False ※前タスクの結果
Thread.Sleep(500);
throw new Exception("なんらかのエラー3");
});
try
{
task.Wait();
}
catch (AggregateException exc)
{
Console.WriteLine(exc.Message);
}
}
}
タスク生成時にTaskContinuationOptionsを渡すことで、
「前タスクがエラー時にだけ実行するタスク」などを作ることができる。
public static class ContinueWithExample2
{
public static void Run()
{
var task = Task.Factory.StartNew(() =>
{
Thread.Sleep(500);
throw new Exception("なんらかのエラー");
})
.ContinueWith((t) =>
{
//実行される
Console.WriteLine("IsFaulted:{0}", t.IsFaulted); //True
Thread.Sleep(500);
//throw new Exception("なんらかのエラー2");
})
.ContinueWith((t2) =>
{
//実行される
Console.WriteLine("IsFaulted:{0}", t2.IsFaulted); //False ※前タスクの結果
Thread.Sleep(500);
throw new Exception("なんらかのエラー3");
})
.ContinueWith((t4) =>
{
//実行される
Console.WriteLine("エラー時タスクを実行します。");
Console.WriteLine("IsFaulted:{0}", t4.IsFaulted); //True
},TaskContinuationOptions.OnlyOnFaulted)
.ContinueWith((t5) =>
{
//前タスクは正常終了した為、実行されない。
Console.WriteLine("エラー時タスク2を実行します。");
Console.WriteLine("IsFaulted:{0}", t5.IsFaulted); //False ※前タスクの結果
}, TaskContinuationOptions.OnlyOnFaulted);
try
{
task.Wait();
}
catch (AggregateException exc)
{
Console.WriteLine(exc.Message);
}
}
}