将HttpClient设置为太短的超时会导致进程崩溃

时间:2013-03-12 14:10:15

标签: c# dotnet-httpclient

我注意到当我使用System.Net.HttpClient短暂超时时,它有时可能会使进程崩溃,即使它被包装在try-catch块中也是如此。这是一个重现这个的简短程序。

public static void Main(string[] args)
{
    var tasks = new List<Task>();
    for (int i = 0; i < 1000; i++)
    {
        tasks.Add(MakeHttpClientRequest());
    }
    Task.WaitAll(tasks.ToArray());

}

private async static Task MakeHttpClientRequest()
{            
    var httpClient = new HttpClient { Timeout = TimeSpan.FromMilliseconds(1) };
    var request = "whatever";
    try
    {
        HttpResponseMessage result =
            await httpClient.PostAsync("http://www.flickr.com/services/rest/?method=flickr.test.echo&format=json&api_key=766c0ac7802d55314fa980727f747710",
                                 new StringContent(request));             
        await result.Content.ReadAsStringAsync();                
    }
    catch (Exception x)
    {
        Console.WriteLine("Error occurred but it is swallowed: " + x);
    }
}

运行此命令会使进程崩溃,但会出现以下异常:

Unhandled Exception: System.AggregateException: One or more errors occurred. ---> System.Net.WebException: The request was canceled
   at System.Net.ServicePointManager.FindServicePoint(Uri address, IWebProxy proxy, ProxyChain& chain, HttpAbortDelegate& abortDelegate, Int32& abortState)
   at System.Net.HttpWebRequest.FindServicePoint(Boolean forceFind)
   at System.Net.HttpWebRequest.get_ServicePoint()
   at System.Net.AuthenticationState.PrepareState(HttpWebRequest httpWebRequest)
   at System.Net.AuthenticationState.ClearSession(HttpWebRequest httpWebRequest)
   at System.Net.HttpWebRequest.ClearAuthenticatedConnectionResources()
   at System.Net.HttpWebRequest.Abort(Exception exception, Int32 abortState)
   at System.Net.HttpWebRequest.Abort()
   at System.Net.Http.HttpClientHandler.OnCancel(Object state)
   at System.Threading.CancellationCallbackInfo.ExecutionContextCallback(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.CancellationCallbackInfo.ExecuteCallback()
   at System.Threading.CancellationTokenSource.CancellationCallbackCoreWork(CancellationCallbackCoreWorkArguments args)
   at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
   --- End of inner exception stack trace ---
   at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
   at System.Threading.CancellationTokenSource.NotifyCancellation(Boolean throwOnFirstException)
   at System.Threading.CancellationTokenSource.TimerCallbackLogic(Object obj)
   at System.Threading.TimerQueueTimer.CallCallbackInContext(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.TimerQueueTimer.CallCallback()
   at System.Threading.TimerQueueTimer.Fire()
   at System.Threading.TimerQueue.FireNextTimers()
   at System.Threading.TimerQueue.AppDomainTimerCallback()

稍微挖掘一下,似乎当HttpClient在创建相关ServicePoint之前中止请求时,HttpWebRequest会尝试通过{{1}创建ServicePoint抛出RequestCanceled。由于在尝试取消请求的线程中抛出此异常,因此不会捕获该异常,并且进程将终止。

我错过了什么吗?你遇到过这个问题吗?

2 个答案:

答案 0 :(得分:20)

HttpWebRequest.Abort()在后​​台/计时器线程上抛出异常。这与HttpClient的任务管理无关。

应在.NET 4.5 GDR1中修复HttpWebRequest.Abort()的异常。 http://support.microsoft.com/kb/2750149 http://support.microsoft.com/kb/2750147

答案 1 :(得分:4)

看起来HttpClient的异步处理程序如何管理任务是一种错误。我能够并行启动项目,但同步运行它们可以正常工作。我不确定你是否想要防止未处理的错误。这会执行并行任务,但自从我关闭它们以后它们并不是异步的。在我的电脑上,我总是会进行5轮,但它会崩溃。即使我在一秒钟后将其设置为超时,也就是如果它们是异步的话,线程中的崩溃仍然会爆炸。

我认为这是一个错误,我无法想象这是预期的行为。

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