等待任务不会传播异常

时间:2019-03-03 16:53:54

标签: c# multithreading

我有一个静态类,具有以下两种方法:

    public async static void Execute()
    {
        var task = new Task<int>(Work);
        try
        {
            task.Start();
            await task;
            Console.WriteLine("This is not reached");
        }
        catch (Exception e)
        {
            Console.WriteLine("This is not reached");
        }
    }

    static int Work()
    {
        Thread.Sleep(500);
        throw new Exception("Oops");
    }

为什么不通过等待任务来传播异常?

1 个答案:

答案 0 :(得分:0)

您的代码有几个“缺陷”。我会尽力为您“修复”它们,但这并不是您问题的实际答案;-)

#subreddit to use
subreddit = reddit.subreddit('test')

#summoning the bot
keyphrase = '!repostfinder'

#find comments with keyphrase
for comment in subreddit.stream.comments():
    if keyphrase in comment.body:
        print('Found keyphrase')
        comment.reply('Keyphrase detected')
        print('Replied to comment')

希望这可以为您澄清一点。

要点:

  • 您很少需要“创建”任务
  • 不使用//please use Task, not void, since the framework //might have trouble determining it's completion public async static Task Execute() { // no need here to call a constructor //var task = new Task<int>(Work); try { //no need to explicitly start //task.Start(); await Work(); Console.WriteLine("This is not reached"); } catch (Exception e) { //this Will be reached :-) Console.WriteLine("This is reached"); } } //we can just make this a task :-) static async Task<int> Work() { //no need to await... but in this case we do.. //... since we throw an exception after the wait. await Task.Delay(500); throw new Exception("Jeuh!"); } ,而是使用async void
  • 始终async Task进行操作:即:尽可能多地创建自己的异步方法
  • 不一定总是等待:您还可以返回任务。
  • 阅读this guy's posts,它们非常好。