如何在HttpWebRequest中实现USING语句(处理)?

时间:2014-04-03 15:15:37

标签: c# .net

我有以下代码,我需要确保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);
    }

1 个答案:

答案 0 :(得分:2)

为了使用using() {}语法,该类必须实现IDisposable。

由于HttpWebRequest没有实现IDisposable,遗憾的是你在这个上运气不好!