相关疑难解决方法(0)

我怎么知道HttpClient何时超时?

据我所知,没有办法知道它特别是发生了超时.我不是在寻找合适的地方,还是我错过了更大的东西?

string baseAddress = "http://localhost:8080/";
var client = new HttpClient() 
{ 
    BaseAddress = new Uri(baseAddress), 
    Timeout = TimeSpan.FromMilliseconds(1) 
};
try
{
    var s = client.GetAsync("").Result;
}
catch(Exception e)
{
    Console.WriteLine(e.Message);
    Console.WriteLine(e.InnerException.Message);
}
Run Code Online (Sandbox Code Playgroud)

返回:

发生了一个或多个错误.

任务被取消了.

c# timeout dotnet-httpclient

123
推荐指数
6
解决办法
11万
查看次数

将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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Unhandled Exception: System.AggregateException: One …
Run Code Online (Sandbox Code Playgroud)

c# dotnet-httpclient

33
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×2

dotnet-httpclient ×2

timeout ×1