问题描述
我尝试用C#开发应用程序,并对MailMessage
对象有一些担忧:
I try to develop an application in C# and have some concerns with MailMessage
object:
它实现了IDisposable
接口,所以我在using
语句中使用它.因此,它在之后隐式调用Dispose
方法.现在,使用该对象,我需要添加附件,这些附件已转换为byte[]
对象,然后将它们添加为流.这是代码的一部分,具有更好的视图:
it implements IDisposable
interface, so I use it within using
statement. So it implicitly calls Dispose
method after. Now, using that object I need to add attachments, which I have converted to byte[]
object and I add them as stream. Here's part of code to have better view:
using(MailMessage message = new MailMessage("[email protected]"){
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
方法),因为在发送消息时会出现错误,因为它在发送时会使用流.
Now, I have one resource unmanaged: Stream
object. I can't close it (so can't call Dispose
method) right after setting attachments, because I'd get an error when sending message, because it uses the stream while sending.
因此,我需要稍后删除它,我在发送后会这样做.那是第二个using
中的代码:
So, I need to get rid of it later, which I do after sending. That's the code in second using
:
try
{
client.Send(messgae);
}
finally
{
if(stream != null)
stream.Dispose();
}
现在出现问题:MailMesssage
的Dispose
方法释放该对象使用的所有资源.我的Stream
对象是资源之一,不是吗?因此,当using(MailMessage...
终止时,它还应该管理我的Stream
对象,不是吗?因此,我不需要手动处置Stream
对象.
Now the question: Dispose
method of MailMesssage
frees all resources used by that object. My Stream
object is one of the resources, isn't it? So, when using(MailMessage...
terminates it should manage also my Stream
object, shouldn't it? So I wouldn't need to dispose of my Stream
object manually.
建议的方法:
using(MailMessage message = new MailMessage("[email protected]"){
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
吗?
But the questions stays: MailMessage
uses this Stream
- so, do we still need to manage Stream
on our own?
推荐答案
从参考文档开始,您无需使用using
.
From the reference documentation you don't need to when you are using using
.
Mail Message disposes Attachment Collection, which then disposes all its attachements.
关于我们应该采用还是依靠这种方法,那么我完全同意佐哈尔的观点
Regarding, should we take or rely on this approach then I totally agree with Zohar on
这篇关于使用另一个IDisposable实现IDisposable的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!