我在生产中遇到了一个奇怪的问题,Windows服务随机挂起,并希望对根本原因分析有任何帮助.
该服务使用C#编写,并部署到使用.NET 4.5的计算机上(尽管我也可以使用.NET 4.5.1重现它).
报告的错误是:
Probable I/O race condition detected while copying memory.
The I/O package is not thread safe by default.
In multithreaded 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.
Run Code Online (Sandbox Code Playgroud)
我已经缩小了异常的来源,以便在记录器中调用Console.WriteLine()和Console.Error.WriteLine().这些从多个线程调用,在高负载下,错误开始出现,服务挂起.
但是,根据MSDN,整个Console类是线程安全的(我之前从多个线程使用它,没有问题).更重要的是,当运行与控制台应用程序相同的代码时,不会出现此问题; 只能从Windows服务.最后,异常的堆栈跟踪显示了对控制台类中的SyncTextWriter的内部调用,该调用应该是异常中提到的同步版本.
有谁知道我做错了什么或错过了一点吗?一个可能的解决方法似乎是将Out和Err流重定向到/ dev/null,但我更喜欢更详细的分析,这似乎超出了我的.NET知识.
我创建了一个repro Windows服务,在尝试时抛出错误.代码如下.
服务类:
[RunInstaller(true)]
public partial class ParallelTest : ServiceBase
{
public ParallelTest()
{
InitializeComponent();
this.ServiceName …Run Code Online (Sandbox Code Playgroud)