簡體   English   中英

在訂閱了一個異步事件后,對象會自動處理嗎?

[英]Will an object be disposed automatically after an asynchronous event it subscribed to is raised?

假設我有一個可以在主線程中多次調用的函數。 每次調用它時,我都會創建一個WebClient對象來異步下載一些數據。

我的問題...這樣做安全嗎? 調用事件后是否釋放WebClient對象? 如果不想自動釋放內存,我不想繼續分配內存。

我的應用程序是使用Silverlight的WP7。

謝謝!

void DownloadData(string cURL)
{
    WebClient webClient = new WebClient();
    webClient.DownloadStringCompleted +=
       new System.Net.DownloadStringCompletedEventHandler(
            webClient_DownloadStringCompleted);
    webClient.DownloadStringAsync(new Uri(cURL));
}

static void webClient_DownloadStringCompleted(object sender,
                      System.Net.DownloadStringCompletedEventArgs e)
{
    ...
}

無需手動處理WebClient,您可以將其放在using塊中。

using (WebClient webClient = new WebClient())
{
    // Your business in here...
}

WebClientSilverLight版本未實現IDisposable 您做對了-時間到了, webClient將被自動垃圾收集。

我看到兩個問題。 首先,不會在所有可能的情況下都處置webclient,其次,將保留對WebClient的引用,因為您永遠不會取消訂閱該事件。

我認為這很接近(盡管仍然不夠完美,請考慮ThreadAborted):

void DownloadData(string cURL) 
        {
            WebClient webClient = new WebClient();

            try
            {
                webClient.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
                webClient.DownloadStringAsync(new Uri(cURL));
            }
            catch
            {
                webClient.Dispose();
                throw;
            }
        }

        static void webClient_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
        {
            WebClient webClient = (WebClient)sender;

            webClient.DownloadStringCompleted -= webClient_DownloadStringCompleted;

            try
            {

            }
            finally
            {
                webClient.Dispose();
            }
        }

WebClient沒有實現iDisposable接口,因此不需要進行任何特殊操作即可進行正確的垃圾收集。 當CLR檢測到當前沒有對該對象的引用時,它將被安排進行垃圾回收。 當然,您不知道何時會發生這種情況,因此可能會或可能不會(很可能不會)立即釋放內存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM