C# 中 Timeout 的处理

前言

最近在项目中要实现一个功能,是关于 Timeout 的,主要是要在要在 TCP 连接建立的时间 和 整个请求完成的时间,在这两个时间层面上,如果超出了设置的时间,就抛出异常,程序中断。

研究了一下项目的代码中,发现在使用HTTP协议,发送请求时,主要用的是微软的 Microsoft.Net.HttpWebRequest 这个类来发起请求和接收请求的。当时我隐约记得这个类怎么有点熟悉呀,好像还有 WebRequstHttpClient 这两个把,还没开始真正开始去了解TimeoutHttpWebRequest中 如何实现的,我先去看了看这三者到底有何不同?

WebRequest , HttpWebRequest , HttpClient

WebRequest 是 一个抽象类,是HttpWebRequest 的父类。是.NET中请求和获取网络中的数据的一个类。

HttpWebRequestWebRequest 的一个实现,不仅对WebRequest中的属性和方法进行了支持,而且还有额外的方法通过Http协议来和服务端交互。

上面那两个现在在微软官方文档上都不推荐使用了,

现在所推荐的是 HttpClient 。由于项目中遗留之前使用的是HttpWebRequest,所以就在原来的基础上进行实现,何况的是在HttpClient中没有找到TCP连接建立的时间属性的设定。

HttpClient 优点自不必多说:

  • 连接池
  • 一次初始化,整个生命周期的重用
  • 和 .Net Core 的融合
  • 以及性能的提升等等

虽然说性能可能提升了,如果你这样用,那也是凉凉

using(HttpClient clinet = new HttpClient())
{
var result = await client.GetAsync("http://aspnetmonsters.com");
Console.WriteLine(result.StatusCode);
}

用完 Using 后,调用了IDispose 接口。那下次还是会重新初始化

这样使用就没问题了

private static HttpClient Client = new HttpClient();

Timeout, ReadWriteTimeout

也可能是我英文的理解能力有点差,在开始我就注意到这个类里面的这两个属性,但是我如何也无法和 TCP 建立前所用的连接时间 与 请求完成的时间联系起来。微软官方文档解释如下:

Timeout

Timeout is the number of milliseconds that a subsequent synchronous request made with the GetResponse method waits for a response, and the GetRequestStream method waits for a stream. The Timeout applies to the entire request and response, not individually to the GetRequestStream and GetResponse method calls. If the resource is not returned within the time-out period, the request throws a WebException with the Status property set to WebExceptionStatus.Timeout.

The Timeout property has no effect on asynchronous requests made with the BeginGetResponse or BeginGetRequestStream method.

ReadWriteTimeout:

The ReadWriteTimeout property is used when writing to the stream returned by the GetRequestStream method or reading from the stream returned by the GetResponseStream method.

Specifically, the ReadWriteTimeout property controls the time-out for the Read method, which is used to read the stream returned by the GetResponseStream method, and for the Write method, which is used to write to the stream returned by the GetRequestStream method.

设置其实是很方便的,如下所示:

HttpWebRequest request = (HttpWebRequest)WebRequest.Creat("<your url>");

//Set timeout to 1s
request.Timeout = 1000; //Set ReadWriteTimeout to 3000
request.ReadWriteTimeout = 3000; HttpWebResponse response = (HttpWebResponse)request.GetResponse();

WebClient.Exception.Timeout 和 OperationCanceledException

最后在捕捉异常的时候,发现了一个很奇怪的地方,就是使用两段代码,却抛出了不同的异常,

第一段代码:

HttpWebRequest request = (HttpWebRequest) WebRequest.Create("https://www.alibabacloud.com");
request.Timeout = 5000;
HttpWebResponse response = (HttpWebResponse) request.GetResponse(); HttpWebRequest request2 = (HttpWebRequest) WebRequest.Create("https://www.cnblogs.com");
request2.Timeout = 1;
HttpWebResponse response2 = (HttpWebResponse) request2.GetResponse(); //Exception
/*
Unhandled Exception: System.Net.WebException: The operation has timed out.
at System.Net.HttpWebRequest.GetResponse()
*/

第二段

HttpWebRequest request = (HttpWebRequest) WebRequest.Create("https://www.alibabacloud.com");
request.Timeout = 5000;
HttpWebResponse response = (HttpWebResponse) request.GetResponse(); request = (HttpWebRequest) WebRequest.Create("https://www.cnblogs.com");
request.Timeout = 1;
response = (HttpWebResponse) request.GetResponse(); //Exception
/*
Unhandled Exception: System.OperationCanceledException: The operation was canceled.
at System.Net.HttpWebRequest.GetResponse()
*/

初步估计的原因是,Http 请求中 Keep-Alive的关系,还有一个可能是 Timeout 的这个说明:

**The Timeout applies to the entire request and response, not individually to the GetRequestStream and GetResponse method calls. ** 然而具体的还没搞清楚,还需要去验证。

后记

其实,设置这两个属性你可能只需要找到文档,分分钟就可以搞定,但是我为什么会在这个过程遇到这些问题呢?一方面是对于C# 中网络请求的不熟悉,其次是找个时间,把以前的代码需要重构一下了,比如把HttpWebRequest 换成 HttpClient 等等。也让我加深了对Http协议的理解。

C# .net 中 Timeout 的处理及遇到的问题的更多相关文章

  1. Angular JS中$timeout的用法及其与window.setTimeout的区别

    $timeout的用法 angular.js的$timeout指令对window.setTimeout做了一个封装,它的返回值是一个promise对象.当定义的时间到了以后,这个promise对象就会 ...

  2. 改变CTS测试中timeout时间

    关键类: JarHostTest.java——>目录:%SOURCE_ROOT%/cts/tools/tradefed-host/src/com/android/cts/tradefed/tes ...

  3. shell中timeout实现

    第一种 function timeout() { waitsec=$SLEEP_TIME ( $* ) & pid=$! ( sleep $waitsec && kill -H ...

  4. AngularJS中$timeout和$interval的用法详解

    1. 先将$interval,$timeout,作为参数注入到controller中,例如rds.controller('controllerCtrl', ['app', '$scope','$htt ...

  5. [转]AngularJS中$timeout和$interval的用法详解

    本文转自:http://www.cnblogs.com/moli-/p/5827618.html 1. 先将$interval,$timeout,作为参数注入到controller中,例如rds.co ...

  6. 关于angular JS 中$timeOut 的一些不正常情况下的$destory

    最近项目中存在的问题头疼脑热了好一会. 我先简单说明下问题是由,使用$timeOut循环调用的时候由于页面存在异步加载会出现反复执行循环反复调用$timeOut,怎么清除跳出循环都不管用.于是查到了如 ...

  7. python 在爬虫中timeout设置超时有什么作用

    是为了防止url不可访问,或者响应速度太慢而造成的时间浪费. 比如,你要爬取1000个网站,如果有100个需要30s才能返回数据,你等待他们返回的话就需要3000s了,如果你设置10s超时,那么就能知 ...

  8. JavaScript 的setTimeout 和Angular中的$timeout的區別

    JavaScript中setTimeout返回值类型和意义说明: 1.setTimeout :暂停指定的毫秒数后执行指定的代码,返回值是id标识,这个id的意义就是通过clearTimeout来清理暂 ...

  9. golang中mysql建立连接超时时间timeout 测试

    本文测试连接mysql的超时时间. 这里的"连接"是建立连接的意思. 连接mysql的超时时间是通过参数timeout设置的. 1.建立连接超时测试 下面例子中,设置连接超时时间为 ...

随机推荐

  1. Python【第二篇】运算符及优先级、数据类型及常用操作、深浅拷贝

    一.运算符及优先级 Python 运算符(算术运算.比较运算.赋值运算.逻辑运算.成员运算) 1.算数运算符 运算符 描述 实例,a=20,b=10 + 加 a+b输出结果30 - 减 a-b输出结果 ...

  2. tensorflow Method源码阅读之 fully_connected

    https://www.tensorflow.org/api_docs/python/tf/contrib/layers/fully_connected fully_connected: 1.先根据权 ...

  3. css浮动(float)全方位案例解析

    前言 浮动最早的使用是出自<img src="#" align="right" />,用于文本环绕图片的排版处理.当然也是一种常用的布局方式. fl ...

  4. 【Unity]】AR小工具-Vuforia

    很有意思的增强现实玩具,六分钟应用. https://www.youtube.com/watch?v=khavGQ7Dy3c

  5. Centos7 安装 scrapy

    Centos7 安装 scrapy ( *:此python版本为 2.7 ) 1.先安装 python (2.7) 在安装 scrapy 要先安装 python 和 pip,  链接:https:// ...

  6. CodeBlocks(17.12) 代码调试基础方法&快捷方式

    转载:CodeBlocks(17.12) 代码调试基础方法&快捷方式: https://www.cnblogs.com/DCD112358/p/8998053.html

  7. WebApi用JilFormatter处理客户端序列化的字符串加密,之后在服务端解析。

    本文有改动,参考原文:https://www.cnblogs.com/liek/p/4888201.html https://www.cnblogs.com/tonykan/p/3963875.htm ...

  8. Python不能用于大型项目?关于Python的10大误解

     语言多元化是PayPal编程文化中一个重要的组成部分.在C++和Java长期流行的同时,更多的团队选择了Jva和Scala.同时,Braintree的收购也引入了一个久经世故的Ruby社区.Pyt ...

  9. torch.utils.data.DataLoader对象中的迭代操作

    关于迭代器等概念参考:https://www.cnblogs.com/zf-blog/p/10613533.html 关于pytorch中的DataLoader类参考:https://blog.csd ...

  10. 【转】【Linux】Swap与Memory

    背景介绍 Memory指机器物理内存,读写速度低于CPU一个量级,但是高于磁盘不止一个量级.所以,程序和数据如果在内存的话,会有非常快的读写速度.但是,内存的造价是要高于磁盘的,且内存的断电丢失数据也 ...