我如何才能知道和HttpClient的超时? [英] How can I tell when HttpClient has timed out?

查看:1726
本文介绍了我如何才能知道和HttpClient的超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,有没有办法知道它的具体发生了超时。我不能找对了地方,还是我失去了一些东西变大?

 字符串baseAddress =HTTP://本地主机:8080 /;
VAR的客户=新的HttpClient()
{
    BaseAddress =新的URI(baseAddress)
    超时= TimeSpan.FromMilliseconds(1)
};
尝试
{
    变种S = client.GetAsync()结果。
}
赶上(例外五)
{
    Console.WriteLine(e.Message);
    Console.WriteLine(e.InnerException.Message);
}

这将返回:


  

发生一个或多个错误。


  
  

一个任务被取消了。



解决方案

您需要等待 GetAsync 方法。然后,它会抛出一个 TaskCanceledException 如果已超时。此外, GetStringAsync GetStreamAsync 内部处理超时,所以他们不会抛出。

 字符串baseAddress =HTTP://本地主机:8080 /;
VAR的客户=新的HttpClient()
{
    BaseAddress =新的URI(baseAddress)
    超时= TimeSpan.FromMilliseconds(1)
};
尝试
{
    变种S =等待client.GetAsync();
}
赶上(例外五)
{
    Console.WriteLine(e.Message);
    Console.WriteLine(e.InnerException.Message);
}

As far as I can tell, there's no way to know that it's specifically a timeout that has occurred. Am I not looking in the right place, or am I missing something bigger?

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

This returns:

One or more errors occurred.

A task was canceled.

解决方案

You need to await the GetAsync method. It will then throw a TaskCanceledException if it has timed out. Additionally, GetStringAsync and GetStreamAsync internally handle timeout, so they will NEVER throw.

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

这篇关于我如何才能知道和HttpClient的超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆