Skip to main content
 首页 » 编程设计

c#之超时不适用于 WebRequest

2024年01月01日51yxwkf

如果我使用下面的代码:

using System; 
using System.Net; 
 
namespace ConsoleApplication1 
{ 
    public class TimeoutWebClient : WebClient 
    { 
        protected override WebRequest GetWebRequest(Uri address) 
        { 
            WebRequest webRequest = base.GetWebRequest(address); 
            webRequest.Timeout = 600000; 
            return webRequest; 
        } 
    } 
 
    class Program 
    { 
        static void Main() 
        { 
            WebClient webClient = new TimeoutWebClient(); 
            webClient.Headers.Add("Referer", @"http://www.finam.ru/analysis/export/default.asp"); 
            string csv = 
                webClient.DownloadString( 
                    "http://195.128.78.52/RIZ1.csv?d=d&market=17&em=75118&p=1&df=23&mf=8&yf=2011&dt=23&mt=8&yt=2011&f=RIZ1&e=.csv&datf=11&cn=RIZ1&dtf=1&tmf=1&MSOR=0&sep=3&sep2=1&at=1"); 
            Console.WriteLine(csv); 
        } 
    } 
} 

然后如果服务器长时间没有应答,我得到一个异常

System.Net.WebException was unhandled 
  HResult=-2146233079 
  Message=The underlying connection was closed: An unexpected error occurred on a receive. 
  Source=System 
  StackTrace: 
       at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) 
       at System.Net.WebClient.DownloadString(Uri address) 
       at System.Net.WebClient.DownloadString(String address) 
       at ConsoleApplication1.Program.Main() in c:\bot\test\webrequest_timeout\ConsoleApplication1\ConsoleApplication1\Program.cs:line 22 
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) 
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) 
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 
       at System.Threading.ThreadHelper.ThreadStart_Context(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.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
       at System.Threading.ThreadHelper.ThreadStart() 
  InnerException: System.IO.IOException 
       HResult=-2146232800 
       Message=Unable to read data from the transport connection: Удаленный хост принудительно разорвал существующее подключение. 
       Source=System 
       StackTrace: 
            at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) 
            at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) 
            at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead) 
       InnerException: System.Net.Sockets.SocketException 
            HResult=-2147467259 
            Message=Удаленный хост принудительно разорвал существующее подключение 
            Source=System 
            ErrorCode=10054 
            NativeErrorCode=10054 
            StackTrace: 
                 at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) 
                 at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) 
            InnerException:  

请您参考如下方法:

看起来它在阅读响应时超时了?然后,您还想通过使用派生类 HttpWebRequest 的 ReadWriteTimeout 属性来设置读/写超时。

参见 http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.readwritetimeout.aspx