我有一个运行大量并发操作的服务,并使用 HttpWebRequest 发出出站请求。
我偶尔会从 GetRequestStream() 调用中得到一个异常,它给出以下堆栈跟踪:
Thread was being aborted.
at System.Threading.WaitHandle.WaitOneNative(SafeHandle waitableSafeHandle, UInt32 millisecondsTimeout, Boolean hasThreadAffinity, Boolean exitContext)
at System.Threading.WaitHandle.InternalWaitOne(SafeHandle waitableSafeHandle, Int64 millisecondsTimeout, Boolean hasThreadAffinity, Boolean exitContext)
at System.Net.LazyAsyncResult.WaitForCompletion(Boolean snap)
at System.Net.Connection.SubmitRequest(HttpWebRequest request, Boolean forcedsubmit)
at System.Net.ServicePoint.SubmitRequest(HttpWebRequest request, String connName)
at System.Net.HttpWebRequest.SubmitRequest(ServicePoint servicePoint)
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
//Rest of stack trace is path to my internal call
我用来发出导致此问题的出站请求的代码如下:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.PathToOutboundAPI.com/ApiCall);
request.Method = "POST";
request.Headers.Add("SOAPAction", Action);
request.ContentType = "text/xml";
request.KeepAlive = false;
request.ServicePoint.Expect100Continue = false;
request.ServicePoint.ConnectionLeaseTimeout = 0; //Dont want Connections staying open
var soapRequest = CreateSoapEnvelope();
byte[] bytes = Encoding.ASCII.GetBytes(soapRequest);
string str = string.Empty;
Stream rs = default(Stream);
WebResponse response = default(WebResponse);
StreamReader reader = default(StreamReader);
try
{
rs = request.GetRequestStream();
rs.Write(bytes, 0, bytes.Length);
response = request.GetResponse();
reader = new StreamReader(response.GetResponseStream());
str = reader.ReadToEnd();
}
catch (WebException exception)
{
//Handle Appropriately
}
catch(Exception exception)
{
//Handle Appropriately
}
finally
{
if (rs != null)
{
rs.Close();
rs.Dispose();
}
if (reader != null)
{
reader.Close();
reader.Dispose();
}
if (response != null)
{
response.Close();
}
}