簡體   English   中英

使用另一個IDisposable實現IDisposable的對象

[英]Objects implementing IDisposable using another IDisposable

我嘗試使用C#開發應用程序,並對MailMessage對象有一些擔憂:

它實現了IDisposable接口,所以我在using語句中使用它。 因此,它在之后隱式調用Dispose方法。 現在,使用該對象,我需要添加附件,這些附件已轉換為byte[]對象,並將它們添加為流。 這是部分代碼,可以更好地查看:

using(MailMessage message = new MailMessage("john.smith@gmail.com"){
    MemoryStream stream;
    //here I pass byte array to the stream and create an attachemnt
    message.Attachments.Add(new Attachment(stream, "name.xyz"));

    using(SmtpClient client = new SmtpClient("server.com", port))
    {
        // send message
    }
}

現在,我有一個不受管理的資源: Stream對象。 設置附件后,我無法立即關閉它(因此無法調用Dispose方法),因為在發送消息時會出現錯誤,因為它在發送時會使用流。

因此,我需要稍后刪除它,我在發送后會這樣做。 那是第二個using的代碼:

try
{
    client.Send(messgae);
}
finally
{
    if(stream != null)
        stream.Dispose();
}

現在的問題是: MailMesssage Dispose方法釋放該對象使用的所有資源。 我的Stream對象是資源之一,不是嗎? 因此,當using(MailMessage...終止時,它還應該管理我的Stream對象,不是嗎?因此,我不需要手動處理Stream對象。

編輯:

建議的方法:

using(MailMessage message = new MailMessage("john.smith@gmail.com"){
    using(MemoryStream stream = ...)
    {
        //here I pass byte array to the stream and create an attachemnt
        message.Attachments.Add(new Attachment(stream, "name.xyz"));

        using(SmtpClient client = new SmtpClient("server.com", port))
        {
            // send message
        }
    }
}

但問題留下: MailMessage使用這個Stream -那么,我們是否還需要管理Stream在我們自己的?

為什么在發送消息后不處理流?

using(MailMessage message = new MailMessage("john.smith@gmail.com"))
{
    using(var stream = new MemoryStream())
    {
        //here I pass byte array to the stream and create an attachemnt
        message.Attachments.Add(new Attachment(stream, "name.xyz"));

        using(SmtpClient client = new SmtpClient("server.com", port))
        {
        // send message
        }
    }
}

嘗試這個:

using(MailMessage message = new MailMessage("john.smith@gmail.com")
using(MemoryStream stream = new MemoryStream())
using(SmtpClient client = new SmtpClient("server.com", port))
{
    message.Attachments.Add(new Attachment(stream, "name.xyz"))
    client.Send(messgae);
}

如果將MemoryStream放在using塊中,它將執行與try/finally塊相同的操作。

從參考文檔中,您不需要using

郵件處理附件集合 ,然后處置所有附件。


關於我們應該采用還是依靠這種方法,我完全同意佐哈爾的觀點

應該通過顯式調用Dispose或使用using語句在代碼中表示對IDisposable的處理。

暫無
暫無

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

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