首页 新闻 会员 周边 捐助

异步任务跑不成功

0
悬赏园豆:30 [已关闭问题] 关闭于 2020-01-22 20:37

开了控制台跑如下代码,断点跑到task1.Result就没了,也没有进task1那个return 3 的方法。请问为什么呢?

static void Main(string[] args)
{
try
{
var task1 = new Task<int>(() => { return 3; });
var task2 = new Task<int>(() => { throw new KeyNotFoundException(); return 3; });
var result1 = task1.Result;
var result2 = task2.Result;
}
catch (AggregateException e) when (e.InnerExceptions.FirstOrDefault().GetType() == typeof(KeyNotFoundException))
{
}

    }
舒碧的主页 舒碧 | 初学一级 | 园豆:169
提问于:2020-01-22 19:57
< >
分享
所有回答(1)
0

new Task 改为 Task.Run

class Program
{
    static void Main(string[] args)
    {
        try
        {
            var task1 = Task.Run(() => { return 3; });
            var task2 = Task.Run(() => { throw new KeyNotFoundException(); return 3; });                

            var result1 = task1.Result;
            var result2 = task2.Result;
        }
        catch (AggregateException e)
        when (e.InnerExceptions.FirstOrDefault().GetType() == typeof(KeyNotFoundException))
        {
            throw e;
        }
    }
}
dudu | 园豆:30734 (高人七级) | 2020-01-22 20:27

如果不使用 Task.Run ,需要调用 Task.Start 方法。

class Program
{
    static void Main(string[] args)
    {
        try
        {
            var task1 = new Task<int>(() => { return 3; });
            var task2 = new Task<int>(() => { throw new KeyNotFoundException(); return 3; });

            task1.Start();
            task2.Start();

            var result1 = task1.Result;
            var result2 = task2.Result;
        }
        catch (AggregateException e)
        when (e.InnerExceptions.FirstOrDefault().GetType() == typeof(KeyNotFoundException))
        {
            throw e;
        }
    }
}
支持(0) 反对(0) dudu | 园豆:30734 (高人七级) | 2020-01-22 20:34
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册