jjzjj

c# - 使用 .NET 4.5 编写的 Windows 服务中的 Console.Out 和 Console.Error 竞争条件错误

coder 2024-06-02 原文

我在生产中遇到了一个奇怪的问题,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.

我已将异常来源缩小为在记录器中调用 Console.WriteLine() 和 Console.Error.WriteLine()。这些从多个线程调用,在高负载下,错误开始出现并且服务挂起。

然而,根据MSDN整个 Console 类是线程安全的(我以前在多个线程中使用过它,没问题)。更重要的是,当运行与控制台应用程序相同的代码时,这个问题不会出现;仅来自 Windows 服务。最后,异常的堆栈跟踪显示控制台类中对 SyncTextWriter 的内部调用,它应该是异常中提到的同步版本。

有谁知道我是否做错了什么或遗漏了一点?一个可能的解决方法似乎是将 Out 和 Err 流重定向到/dev/null,但我更喜欢更详细的分析,这似乎超出了我对 .NET 的了解。

我创建了一个重现 Windows 服务,在尝试时会抛出错误。代码如下。

服务类:

[RunInstaller(true)]
public partial class ParallelTest : ServiceBase
{
    public ParallelTest()
    {
        InitializeComponent();
        this.ServiceName = "ATestService";
    }

    protected override void OnStart(string[] args)
    {
        Thread t = new Thread(DoWork);
        t.IsBackground = false;

        this.EventLog.WriteEntry("Starting worker thread");
        t.Start();

        this.EventLog.WriteEntry("Starting service");
    }

    protected override void OnStop()
    {
    }

    private void DoWork()
    {
        this.EventLog.WriteEntry("Starting");
        Parallel.For(0, 1000, new ParallelOptions() { MaxDegreeOfParallelism = 10 }, (_) =>
        {
            try
            {
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine("test message to the out stream");
                    Thread.Sleep(100);
                    Console.Error.WriteLine("Test message to the error stream");
                }
            }
            catch (Exception ex)
            {
                this.EventLog.WriteEntry(ex.Message, EventLogEntryType.Error);
                //throw;
            }
        });
        this.EventLog.WriteEntry("Finished");
    }
}

主类:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
        // Remove comment below to stop the errors
        //Console.SetOut(new StreamWriter(Stream.Null));
        //Console.SetError(new StreamWriter(Stream.Null));

        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
        { 
            new ParallelTest() 
        };
        ServiceBase.Run(ServicesToRun);
    }
}

安装类:

partial class ProjectInstaller
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary> 
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Component Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
        this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
        // 
        // serviceProcessInstaller1
        // 
        this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
        this.serviceProcessInstaller1.Password = null;
        this.serviceProcessInstaller1.Username = null;
        // 
        // serviceInstaller1
        // 
        this.serviceInstaller1.ServiceName = "ATestServiceHere";
        // 
        // ProjectInstaller
        // 
        this.Installers.AddRange(new System.Configuration.Install.Installer[] {
        this.serviceProcessInstaller1,
        this.serviceInstaller1});

    }

    #endregion

    private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
    private System.ServiceProcess.ServiceInstaller serviceInstaller1;
}

使用 InstallUtil.exe 安装此服务并启动它会在事件日志中记录错误。

最佳答案

Console.Out 和 Console.Error 都是线程安全的,因为它们各自为控制台输出和错误流 TextWriters 返回一个线程安全的包装器(通过 TextWriter.Synchronized)。但是,此线程安全仅适用于 Console.Out 和 Console.Error 是不同流的 TextWriters 的情况。

您的代码在作为 Windows 服务运行时抛出异常的原因是,在这种情况下,输出和错误 TextWriters 都设置为 StreamWriter.Null,这是一个单例。您的代码同时调用 Console.WriteLine 和 Console.Error.WriteLine,当一个线程碰巧在另一个线程调用 Console.Error.WriteLine 的同时调用 Console.WriteLine 时,这会导致异常。这会导致同时从 2 个线程写入同一流,从而导致“复制内存时检测到可能的 I/O 竞争条件”。异常(exception)。如果你只使用Console.WriteLine或者只使用Console.Error.WriteLine,你会发现异常不再出现。

这是演示该问题的最小非服务控制台程序:

using System;
using System.IO;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        var oldOut = Console.Out;
        var oldError = Console.Error;

        Console.SetOut(StreamWriter.Null);
        Console.SetError(StreamWriter.Null);
        Parallel.For(0, 2, new ParallelOptions() { MaxDegreeOfParallelism = 2 }, (_) =>
        {
            try
            {
                while(true)
                {
                    Console.WriteLine("test message to the out stream");
                    Console.Error.WriteLine("Test message to the error stream");
                }
            }
            catch (Exception ex)
            {
                Console.SetOut(oldOut);
                Console.SetError(oldError);
                Console.WriteLine(ex);
                Environment.Exit(1);
            }
        });
    }
}

关于c# - 使用 .NET 4.5 编写的 Windows 服务中的 Console.Out 和 Console.Error 竞争条件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33915790/

有关c# - 使用 .NET 4.5 编写的 Windows 服务中的 Console.Out 和 Console.Error 竞争条件错误的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  7. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  8. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  9. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  10. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

随机推荐