StringWriter内存超出范围异常

时间:2015-11-09 02:30:04

标签: asp.net-mvc json.net out-of-memory stringwriter

我有一个方法_,它会在public class SAPISIDHASH { public static void main(String [] args) { String sapisid = "b4qUZKO4943exo9W/AmP2OAZLWGDwTsuh1"; String origin = "https://hangouts.google.com"; String sapisidhash = "1447033700279" + " " + sapisid + " " + origin; System.out.println("SAPISID:\n"+ hashString(sapisidhash)); System.out.println("Expecting:"); System.out.println("38cb670a2eaa2aca37edf07293150865121275cd"); } private static String hashString(String password) { String sha1 = ""; try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(password.getBytes("UTF-8")); sha1 = byteToHex(crypt.digest()); } catch(NoSuchAlgorithmException e) { e.printStackTrace(); } catch(UnsupportedEncodingException e) { e.printStackTrace(); } return sha1; } private static String byteToHex(final byte[] hash) { Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } String result = formatter.toString(); formatter.close(); return result; } } 行投放ExecuteResult。发生这种情况是因为System.OutOfMemoryException对象在内存中对于Response.Write(sw.ToString())而言太大;它填满了记忆。

我一直在寻找解决方案,但似乎无法找到问题的简单清洁解决方案。任何想法都将不胜感激。

代码:

StringWriter

1 个答案:

答案 0 :(得分:1)

我认为问题在于您将所有JSON缓冲到StringWriter中,然后尝试将其写入一个大块而不是将其流式传输到响应中。

尝试替换此代码:

using (var sw = new StringWriter())
{
    scriptSerializer.Serialize(sw, this.Data);
    //outofmemory exception is happening here
    response.Write(sw.ToString());
}

有了这个:

using (StreamWriter sw = new StreamWriter(response.OutputStream, ContentEncoding))
using (JsonTextWriter jtw = new JsonTextWriter(sw))
{
    scriptSerializer.Serialize(jtw, this.Data);
}