LoginSignup
3
3

More than 5 years have passed since last update.

継続タスクで例外発生した場合の挙動

Last updated at Posted at 2014-11-29

継続タスク途中で未補足な例外が発生しても後続のタスクは実行される。

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);
        }
    }
}
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3