Task,带返回值的Task


Task.Wait(),Task.Result都调用InternalWait方法

Task.WhenAll<TResult>()

Task.WhenAny<TResult>()

 

 public static void DoSomething()
        {
            Task<int> task1 = Task.Factory.StartNew(() =>
            {
                //做一些逻辑运算
                return 1;
            });

            Task<int> task2 = Task.Factory.StartNew(() =>
            {
                //做一些逻辑运算
                return 2;
            });

            var task = Task.WhenAll<int>(new Task<int>[2] { task1, task2 }).ContinueWith(x =>
            {
                //do something
            });
        }

  

异常处理

AggregateException 

 try
            {
                Task<int> t = Task.Factory.StartNew(() =>//这里不要使用Task.Run方法,它默认DenyChildAttach
                {
                    Task t1 = Task.Factory.StartNew(() =>
                    {
                        throw new Exception("exception 1");
                    }, TaskCreationOptions.AttachedToParent);

                    Task t2 = Task.Factory.StartNew(() =>
                    {
                        throw new Exception("exception 2");
                    }, TaskCreationOptions.AttachedToParent);

                    return 1;
                });

                try
                {
                    t.Wait();
                }
                catch (AggregateException ex)
                {
                    ex.Handle(x =>//handle方法遍历AggregateException ,ex1返回true处理完成,ex2返回false会放到新的异常聚集里向上抛出
                    {
                        if (x.InnerException.Message.Contains("1"))
                            return true;
                        return false;
                    });
                    throw;
                }
            }
            catch (AggregateException ex)//AggregateException 中只剩exception2了
            {
                throw;
            }

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM