使用HttpWebRequest下载时如何克服高内存

时间:2011-12-09 01:25:16

标签: windows-phone-7

在我的项目中,我使用HttpWebRequest下载Feed。但是当我下载时,内存会增加,而不是在返回上一个表单时减少:

#region RequestDataFromServer
private void RequestDataFromServer(object o)
{
    if (!string.IsNullOrEmpty(ServerUri))
    {
        if (DownloadStatus == DownloadState.Downloading)
            return;
        DownloadStatus = DownloadState.Downloading;

        HttpWebRequest serverRequest = (HttpWebRequest)WebRequest.Create(ServerUri);
        serverState = new ServerRequestUpdateState();
        serverState.AsyncRequest = serverRequest;

        IAsyncResult result =
(IAsyncResult)serverRequest.BeginGetResponse(new AsyncCallback(RequestResponse), serverState);

    }
}
#endregion

#region RequestResponse
void RequestResponse(IAsyncResult asyncResult)
{
    var offlineStream = IsolatedStorageSettings.ApplicationSettings;
    serverState = (ServerRequestUpdateState)asyncResult.AsyncState;
    HttpWebRequest serverRequest = (HttpWebRequest)serverState.AsyncRequest;
    try
    {
        serverState.AsyncResponse = (HttpWebResponse)serverRequest.EndGetResponse(asyncResult);
        if (serverState != null)
        {
            Stream stream = serverState.AsyncResponse.GetResponseStream();
            if (stream != null && serverState.AsyncResponse.StatusCode == HttpStatusCode.OK)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    DownloadStatus = DownloadState.FileReady;
                    if (serverState != null)
                    {
                        try
                        {
                            if (offlineStream.Contains("streamOffline"))
                            {
                                offlineStream["streamOffline"] = null;
                                offlineStream.Remove("streamOffline");
                            }
                            offlineStream.Add("streamOffline", stream);


                            if (onComplete != null)
                                onComplete.Invoke(this, DownloadStatus, IndexImg);
                            stream.Close();
                            stream.Dispose();
                            stream = null;
                        }
                        catch (Exception)
                        { }
                    }
                });
            }
        }
    }
    catch (WebException ex)
    {
        DownloadStatus = DownloadState.Error;
        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
            //if (onComplete != null)
            //    onComplete.Invoke(this, DownloadStatus, null, IndexImg);
        });
    }
    catch (Exception)
    { }
    finally
    {
        serverRequest = null;
    }
}
#endregion

我以为我已经摧毁了所有可以增加内存的东西,但内存仍然非常高,我保存了Isostorage Stream,但它仍然没有减少

1 个答案:

答案 0 :(得分:0)

在.NET处理对象时,内存不会减少。当GC下次启动时会下降。

详细了解... http://msdn.microsoft.com/en-us/magazine/bb985010.aspx

你如何确定记忆力很高?