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

本文关键字:语句 处置 USING 实现 HttpWebRequest | 更新日期: 2023-09-27 17:56:21

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

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

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

由于HttpWebRequest没有实现IDisposable,不幸的是,你不走运!