Setting HttpClient to a too short timeout crashes process

前端 未结 2 1851
南方客
南方客 2021-01-31 03:40

I\'ve noticed that when I\'m using System.Net.HttpClient with a short timeout, it may sometimes crash the process, even when it is wrapped in a try-catch block. Her

相关标签:
2条回答
  • 2021-01-31 03:50

    Looks like it's some kind of bug in how the async handler for HttpClient is managing the tasks. I was able to launch the items in parallel, but run them synchronously and it works. I'm not sure if you want to just prevent the unhandled error or not. This ran parallel tasks, but they aren't async really since I turned it off. On my computer I would always get to 5 rounds and it would crash. Even if i set it to timeout after a second, it's like the crashes in the threads would still blow up if they were async.

    I think it's a bug, I can't imagine this is intended behavior.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Net.Http;
    
    namespace TestCrash
    {
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    Parallel.ForEach(Enumerable.Range(1, 1000).ToList(), i =>
                    {
                        Console.WriteLine(i);
                        using (var c = new HttpClient { Timeout = TimeSpan.FromMilliseconds(1) })
                        {
                            var t = c.GetAsync("http://microsoft.com");
                            t.RunSynchronously(); //<--comment this line and it crashes
                            Console.WriteLine(t.Result);
                        }
                    });
                }
                catch (Exception x)
                {
                    Console.WriteLine(x.Message);
                }
                Console.ReadKey();
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-31 03:59

    HttpWebRequest.Abort() is throwing an exception on a background/timer thread. This has nothing to do with HttpClient's Task management.

    The exception from HttpWebRequest.Abort() should be fixed in .NET 4.5 GDR1. http://support.microsoft.com/kb/2750149 http://support.microsoft.com/kb/2750147

    0 讨论(0)
提交回复
热议问题