HY,
在我的项目中,我使用 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 资源未关闭。我有以下问题:
任何澄清都非常有用。 感谢
答案 0 :(得分:1)
您可以尝试同步stringTemplate对象上的访问。
我的猜测是,如果您同时修改它并阅读或修改它,您只需要同步。如果您只是阅读它,通常不重要。
lock (stringTemplate)
{
// Access thread-sensitive resources.
}
出于效率原因,您应该保持同步块尽可能小;只需使用stringTemplate访问。
答案 1 :(得分:1)
我最近遇到了同样的错误! 查看堆栈跟踪:它是从ConsoleErrorListener抛出的。 简而言之,抛出异常是因为两个线程正在尝试写入Console.Out流。 要消除此错误,您应该覆盖模板的错误处理程序。
标记为答案的解决方案将起作用,但会有太多的锁争用。