我编写了一个C#程序,它每5秒发布一次HTTP心跳请求,它在开始时运行良好,但在大约20-40分钟之后,它继续在方法HttpWebRequest.BeginGetRequestStream()(或HttpWebResponse.EndGetResponse)上抛出webException。 ()如果我不需要发布数据)。
我在一些特定的计算机上遇到了这个问题,这些计算机的性能并不好。
我做了几次尝试,但仍然得到了相同的结果:
这是异常堆栈跟踪:
System.Net.WebException: the underlying connection was closed:unable to connect to the remote server.
---> System.Net.Sockets.SocketException: an invalid argument was supplied.
at System.Net.Sockets.Socket..ctor(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout)
at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback)
at System.Net.Connection.CompleteStartConnection(Boolean async, HttpWebRequest httpWebRequest)
这是我的代码的核心部分:
public MainWindow()
{
InitializeComponent();
timer = new Timer(new TimerCallback(delegate (object obj)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.KeepAlive = false;
IAsyncResult result = request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), request, 15000, true);
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}), null, Timeout.Infinite, Timeout.Infinite);
}
private void TimeoutCallback(object state, bool timeout)
{
if (timeout)
{
HttpWebRequest request = state as HttpWebRequest;
if (request != null)
{
request.Abort();
}
}
}
private void ResponseCallback(IAsyncResult result)
{
try
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string responseString = reader.ReadToEnd();
responseStream.Close();
reader.Close();
response.Close();
Console.WriteLine(responseString);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
我认为代码没有任何问题,也许是.net问题或网络问题,如果有人给我一些建议,我将非常感激。