Update for future readers: If you find this text too long: This is a race condition due to a static variable. What you are reading below is showing how confusing this can become for someone who is debugging it and overlooking the static
keyword. If you are experiencing similar behaviour always check for static
first.
I am debugging this application, but cannot find a bug in the code. The class of my master page has a private property called Greeting
. This property does not cause trouble until two users on the same server log out at about the same time (within less than one second). Then one user gets the greeting that was meant for the other user (for example, if John and Jane were testing, both would see "Dear Misses Jane!").
So, for debugging purposes I implemented a getter and a setter for this property. Both write the value that is read or written to the trace.axd via HttpContext.Current.Trace.Write()
. I am seeing that the correct value is set. But in the last get
the value of the corresponding other user is read.There are two consecutive calls of the getter that return different values. There is no call to the setter inbetween. The property is private, and code analysis is showing, that it is not referenced from anywhere else. I am also writing the stack trace to the trace with Environment.StackTrace
. Code is running as expected. How can this be anything different than an error in .NET itself?
private static string _Greeting = String.Empty;
private static string Greeting
{
get
{
System.Web.HttpContext.Current.Trace.Write("Debug", "myMasterPage.Greeting__get(): " + _Greeting);
System.Web.HttpContext.Current.Trace.Write("Debug", "myMasterPage.Greeting__get() STACKTRACE: " + Environment.StackTrace);
return _Greeting;
}
set
{
_Greeting = value;
System.Web.HttpContext.Current.Trace.Write("Debug", "myMasterPage.Greeting__set(): " + _Greeting);
System.Web.HttpContext.Current.Trace.Write("Debug", "myMasterPage.Greeting__set() STACKTRACE: " + Environment.StackTrace);
}
}
Excerpt of the Trace (with pseudonyms):
Debug myMasterPage.Greeting__get(): Dear Misses Jane
Debug myMasterPage.Greeting__get(): Dear Mister John