[英]How to implement USING statement (disposal) in HttpWebRequest?
I have following code, I would need make sure that HttpWebRequest it is always disposed. 我有以下代码,我需要确保HttpWebRequest始终处理。
How should I modify my code? 我应该如何修改我的代码?
private static void CheckIsConnectedToInternet()
{
string urlToCheck = utility.GetConfiguration("device", "checkInternetUrl");
int timeOut = Convert.ToInt32(utility.GetConfiguration("device", "checkInternetTimeOurMs"));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(urlToCheck);
webRequest.Timeout = timeOut;
// Init your request...then:
DoWithResponse(webRequest, (response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
isConnectedToInternet = true;
else
isConnectedToInternet = false;
});
}
private static void DoWithResponse(HttpWebRequest request, Action<HttpWebResponse> responseAction)
{
Action wrapperAction = () =>
{
request.BeginGetResponse(new AsyncCallback((iar) =>
{
try
{
var response = (HttpWebResponse)((HttpWebRequest)iar.AsyncState).EndGetResponse(iar);
responseAction(response);
}
catch
{
isConnectedToInternet = false;
}
}), request);
};
wrapperAction.BeginInvoke(new AsyncCallback((iar) =>
{
var action = (Action)iar.AsyncState;
action.EndInvoke(iar);
}), wrapperAction);
}
In order to use the using() {}
syntax the class must implement IDisposable. 为了使用using() {}
语法,该类必须实现IDisposable。
As HttpWebRequest does not implement IDisposable unfortunately you are out of luck on this one! 由于HttpWebRequest没有实现IDisposable,不幸的是你在这个上运气不好!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.