取消异步httpwebrequests [英] Canceling async httpwebrequests
问题描述
我在做一个应用程序,这将使一些HttpWebRequest的对象和下载通过 HTT prequest.BeginGetResponse
方法我的HTML。我回来了的IAsyncResult
并存储在本地,这样我可以随时取消请求,但我不知道如果我正确地这样做。
I am making an app that will make several HttpWebRequest objects and downloading my html via the httpRequest.BeginGetResponse
method. I get back the IAsyncResult
and store it locally so that I can cancel the request at any time, but I'm not sure if I'm doing that correctly.
下面是我在做什么,以取消异步Web请求:
Here is what I'm doing to cancel the async web request:
var res = (RequestState)asyncResult.AsyncState;
res.Request.Abort();
在哪里请求的类型为的HttpWebRequest
。
什么我注意到的是,即使是在我称之为code的这些线,我仍然有所有的异步线程在我的应用程序打开的。如果我设置叫 HTT prequest.BeginGetResponse(GetResponseCallback,州)
(如方法 GetResponseCallback 委托一个破发点code>)的方法中的调试器中断几秒钟后,引起引发WebException时方法跑到被抛出。
What I'm noticing is that even after I call these lines of code, I still have all of the Async threads open in my application. And if I set a break point in the delegate called in httpRequest.BeginGetResponse(GetResponseCallback, state)
(e.g. the method GetResponseCallback
) The debugger breaks inside the method after a few seconds, causing a WebException to be thrown when that method is ran.
只是为了保持完整性,我GetResponseCallback看起来是这样的:
Just for completeness, my GetResponseCallback looks like this:
using (var httpWebResponse = (HttpWebResponse)request.EndGetResponse(result))
using (Stream dataStream = httpWebResponse.GetResponseStream())
using (var reader = new StreamReader(dataStream))
{
string ret = reader.ReadToEnd();
state.OnComplete(ret, new EventArgs());
}
和我上使用(流数据流= httpWebResponse.GetResponseStream())
行引发WebException。内部异常类似于服务器主动拒绝了连接像什么的。
and I get the WebException on the using (Stream dataStream = httpWebResponse.GetResponseStream())
line. The inner exception says something like "the server actively refused the connection" or something like that.
任何帮助将是极好的!
推荐答案
Abort方法取消对资源的请求。请求被取消后,调用GetResponse的,BeginGetResponse,EndGetResponse,GetRequestStream,BeginGetRequestStream或EndGetRequestStream方法使设置为RequestCanceled Status属性引发WebException。
The Abort method cancels a request to a resource. After a request is canceled, calling the GetResponse, BeginGetResponse, EndGetResponse, GetRequestStream, BeginGetRequestStream, or EndGetRequestStream method causes a WebException with the Status property set to RequestCanceled.
所以,你所描述的行为是设计使然。我认为你必须捕捉异常,否则找决定是否中止打电话之前调用的一些方法的GetResponse,BeginGetResponse,EndGetResponse,GetRequestStream,BeginGetRequestStream或EndGetRequestStream。
So the behavior you describe is by design. I think you'll have to catch the exception, or else find some way of determining whether Abort was called before calling GetResponse, BeginGetResponse, EndGetResponse, GetRequestStream, BeginGetRequestStream, or EndGetRequestStream.
这篇关于取消异步httpwebrequests的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!