c# - StringWriter.ToString() 处的 OutOfMemoryException

标签 c# .net out-of-memory

在我的 StringWriter 上调用 ToString 时出现 OutOfMemoryException:

StringWriter stringWriter = new System.IO.StringWriter();
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(stringWriter, data);
string xmlString = stringWriter.ToString(); // <-- Exception occurs here

我该如何解决这个问题?

最佳答案

试试这段代码。它使用文件作为临时缓冲区。

List<Dummy> lst = new List<Dummy>();

        for (var i = 0; i < 100000; i++)

        {
            lst.Add(new Dummy()
                    {
                        X =  i,
                        Y =  i * 2
                    });

        }

        XmlSerializer serializer = new XmlSerializer(typeof(List<Dummy>));

        // estimate your memory consumption ... it would be around 4 bytes reference + 4 bytes object type pointer + 8 bytes those ints + let's say another 4 bytes other hidden CLR metadatas. a total of 20 bytes per instance + 4 bytes reference to our object (in the list array) => around 24 bytes per instance. Round up to a let's say 50 bytes per instance. Multiply it by 100.000 = 5.000.000

        MemoryStream memStream = new MemoryStream(5000000);

        serializer.Serialize(memStream, lst);
        memStream.Position = 0;

        string tempDatafileName = null;
        var dataWasWritten = false;
        try
        {
            var fileName = Guid.NewGuid().ToString() + ".tempd";
            var specialFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);

            using (var fs = new FileStream(tempDatafileName, FileMode.Create, FileAccess.ReadWrite))
                memStream.WriteTo(fs);

            dataWasWritten = true;

            memStream.Dispose();
            memStream = null;

            lst.Clear();
            lst = null;
            // force a full second generational GC
            GC.Collect(2);

            // reading the content in string
            string myXml = File.ReadAllText(tempDatafileName);
        }
        finally
        {
            if (dataWasWritten && string.IsNullOrWhiteSpace(tempDatafileName) == false)
            {
                if (File.Exists(tempDatafileName))
                {
                    try
                    {
                        File.Delete(tempDatafileName);
                    }
                    catch
                    {

                    }
                }
            }
        }

关于c# - StringWriter.ToString() 处的 OutOfMemoryException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31446657/

相关文章:

java - 制作多图安卓游戏,如何避免多图报java.lang.OutOfMemory错误

c# - .NET framework 如何为 OutOfMemoryException 分配内存?

c# - 为什么我的表单在尝试加载图像时抛出 OutOfMemory 异常?

c# - 有条件地组合两个 Rx 流

C# 指针上的指针

c# - 在 Prism 应用程序的多个模块中使用的模型应该放在哪里?

c# - DAL 和 BLL 应该通过的类型

c# - CLR 什么时候说一个对象有终结器?

c# - 是否有用于 Firefox 或 Chrome 的 .Net 包装器来抓取网页?

c# - 如何确定 ASP .NET JSON WebService 的 JSON 数据输入格式?