nhibernate race condition when loading entity

后端 未结 2 501
遥遥无期
遥遥无期 2020-12-29 10:53

I have a problem with a nhibernate race condition in my webapp.

I am aware of this happening when using older versions of log4net (should be fixed in 1.2.10), althou

相关标签:
2条回答
  • 2020-12-29 11:23

    Stamppot, thank you for posting this problem to StackOverflow; as you know, there is not much other information about this error message to be found on the Web. My team ran into a similar problem a few months ago in a webapp that uses NHibernate and log4net. (StringTemplate might have been involved too.) We "fixed" the problen by redirecting Console.Out/Error to null streams (effectively disabling them) in the Application_Start() event handler in Global.ascx.cs:

    protected void Application_Start(object sender, EventArgs e)
    {
        Console.SetOut(new System.IO.StreamWriter(System.IO.Stream.Null));
        Console.SetError(new System.IO.StreamWriter(System.IO.Stream.Null)); 
    }
    

    Details: In our case, the "probable race condition..." error was related to load. On the production server, this exception would arise sporadically, crashing the worker process on each occasion. Eventually we found out how to reproduce it, by running a script that flooded the webapp with many requests in a short period of time. The exception stack traces, when correlated with the NHibernate/StringTemplate/log4net source code, pointed to the use of Console.Out/Error methods for logging in various situations. Seems like a strange place for such an error to arise---aren't these methods considered to be thread-safe? However, after we applied the above workaround, the problem immediately disappeared and hasn't returned since. Unfortunately, other priorities kept us from digging deeper---but whatever the root cause of the problem, it hasn't manifested itself in any other way.

    0 讨论(0)
  • 2020-12-29 11:35

    The problem with solution that @APW provided is that by default, StreamWriter is not thread safe. Check it here: https://msdn.microsoft.com/en-us/library/system.io.streamwriter(v=vs.110).aspx

    By passing "new StreamWriter" to Console.Set* you are passing non-thread safe instance. So I think it's a matter of time to see similar error again.

    Correct way would be using TextWriter.Synchronized method to wrap unsafe Stream.Null.

    using System.IO;
    ...
    var nullStream = TextWriter.Synchronized(TextWriter.Null);
    Console.SetOut(nullStream);
    Console.SetError(nullStream);
    

    UPD: Please ignore this. I have found that Console.SetOut wrapping any stream into TextWriter.Synchronized(...). Proof.

    0 讨论(0)
提交回复
热议问题