我有以下代码,我需要确保HttpWebRequest始终处理它。
我应该如何修改我的代码?
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);
}
答案 0 :(得分:2)
为了使用using() {}
语法,该类必须实现IDisposable。
由于HttpWebRequest没有实现IDisposable,遗憾的是你在这个上运气不好!