【发布时间】:2015-03-17 13:10:59
【问题描述】:
喂,
在我的项目中,我使用 Antlr.StringTemplate.StringTemplateGroup 类来创建本地化模板。我访问 .st 文件并设置所需的属性如下。
public StringTemplate WrapValuesReportTemplateContent(
private StringTemplateGroup StringTemplateGroup = new StringTemplateGroup(StringTemplateGroupName);
StringTemplate stringTemplate = this.StringTemplateGroup.GetInstanceOf(path);
stringTemplate.SetAttribute("atr1", value1);
stringTemplate.SetAttribute("atr2", value2);
return stringTemplate
)
该类被经理重复使用,因此触发了以下异常。
System.IndexOutOfRangeException: Probable I/O race condition detected while copying memory. The I/O package is not thread safe by default. In multithread applications, a stream must be accessed in a thread-safe way, such as a thread-safe wrapper returned by TextReader's or TextWriter's Synchronized methods. This also applies to classes like StreamWriter and StreamReader.
at System.Buffer.InternalBlockCopy(Array src, Int32 srcOffsetBytes, Array dst, Int32 dstOffsetBytes, Int32 byteCount)
at System.IO.StreamWriter.Write(Char[] buffer, Int32 index, Int32 count)
at System.IO.TextWriter.WriteLine(String value)
at System.IO.TextWriter.SyncTextWriter.WriteLine(String value)
at Antlr.StringTemplate.ConsoleErrorListener.Error(String s, Exception e)
at Antlr.StringTemplate.StringTemplate.BreakTemplateIntoChunks()
我对 StringTemplate 很陌生,我不清楚 StringTemplates 是如何工作的。从错误描述中我了解到 .st 资源没有关闭。我有以下问题:
- 在创建新的 StringTemplate 时,我们会创建一个 Stream 用于写入和读取 .st 文件,或者我们修改属性的新对象
- .st 文件打开后是否会在超出范围时自动关闭
- 为了避免此错误,最好的方法是什么。我们应该对资源使用锁,还是将所有内容都包装在 using 中?
任何澄清都会非常有用。 谢谢
【问题讨论】:
-
您是否从多个线程访问模板?
-
是的,它是一个多线程应用程序。
-
你的问题有更详细的答案here
标签: race-condition stringtemplate