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
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();
}
}
}