C# 内存使用:Team Foundation Server dll 中流 class 使用的值与引用类型

C# memory usage: value vs reference type for stream class usage in Team Foundation Server dlls

我按照此处的示例 (How to attach a file to work item in TFS without physical file path?) 将文件附加到 TFS 中的工作项,方法是使用流而不是物理文件。我有以下代码:

internal static void AddAttachment(WorkItemServer server, Project teamProject, string fileContent, WorkItem workItem)
{
    FileAttachment attachment = new FileAttachment();
    using (MemoryStream stream = new MemoryStream())
    {
        using (StreamWriter writer = new StreamWriter(stream))
        {
            writer.Write(fileContent);
            writer.Flush();
            stream.Position = 0;

            attachment.LocalFile = stream;
            attachment.AreaNodeUri = "";
            attachment.FileNameGUID = Guid.NewGuid();
            attachment.ProjectUri = teamProject.Uri.ToString();

            server.UploadFile(attachment);

            const string c_UpdatePackage = @"<validxml>";
            XmlDocument updatePackage = new XmlDocument();
            updatePackage.LoadXml(string.Format(c_UpdatePackage, workItem.Id /*work item ID*/, workItem.Rev /*work item latest revision*/, "Test attachment", attachment.FileNameGUID, DateTime.Now.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'"), fileContent.Length, "John Smith", "http://localhost:8080/tfs/defaultcollection"));

            XmlElement outputPackage;
            string dbStamp;
            IMetadataRowSets metadata;
            server.Update(Guid.NewGuid().ToString(), updatePackage.DocumentElement, out outputPackage, null, out dbStamp, out metadata);
        }
    }
}

我的问题:作业中

attachment.LocalFile = stream;

流是通过引用还是通过值复制到 attachment.LocalFile?如果它是通过引用复制的,我认为上面的代码不会有内存泄漏,因为它正在使用中处理流:

using (MemoryStream stream = new MemoryStream()) { ... }

但是如果它按值复制(制作流的副本),这将导致内存泄漏,因为 FileAttachment 没有被释放,对吧?如果存在内存泄漏,我认为无法修复此内存泄漏,因为 FileAttachment 未继承 IDisposable。以下是 FileAttachment 的反编译代码 resharper 显示:

namespace Microsoft.TeamFoundation.WorkItemTracking.Proxy
{
    public struct FileAttachment
    {
        private Stream m_localFile;
        ...
        public Stream LocalFile
        {
            get
            {
                return this.m_localFile;
            }
            set
            {
                this.m_localFile = value;
            }
        }
    }
 }

我们如何确认流对象是按引用还是按值复制的?如果是按值复制,我们如何才能阻止内存泄漏?

如果对象是 class,则对象是引用类型,而 value type if it is a struct or enumerable. FileAttachmentclass

因此,赋值 attachment.LocalFile = stream; 不会导致内存泄漏,因为它是通过引用赋值进行复制。

还应注意,attachment.LocalFile 属性 一旦退出 using() 作用域,将指向无效数据,如果有任何尝试访问,将抛出异常属性.