[英]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
塊相同的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.