As a school project we’ve created a C# XNA 4.0 Game that runs perfectly when run (in either Release or Debug) from Visual Studio 2010 itself. However, when it’s built, the game inexplicably crashes at a certain point.
The responsible code portion seems to be this:
while( true )
{
if( Client.readInfo )
{
t.Stop();
t.Dispose();
// Save last good IP to file
string toWrite = IPinput.filledIn;
using( StreamWriter file = new StreamWriter( "multiplayer.dat", false ) )
{
file.WriteLine( toWrite );
}
ExitScreen();
using( LobbyScreen screen = new LobbyScreen( c ) )
{
screenManager.AddScreen( screen );
}
break;
}
else if( itTookToLong )
{
Client.killMe = true;
IPinput.Text = "Server IP: ";
IPinput.filledIn = "";
break;
}
}
This waits till the started Client thread makes the public static attribute readInfo true (which happens, because the server obtains the client) or a timer runs out after 10 seconds. Both things work perfectly fine when running through VS, but the game just stops responding when run as built EXE.
What could this be?!
Edit: I seem to have found the fix already, FINALLY. Adding Thread.Sleep(1); at the bottom of the above while(true) loop seems to fix all problems! Don’t know why this is different between running an EXE and running from Visual Studio though, but hey it works.
Edit2: This site explains my whole problem: http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/
Thread.Sleep just accidentally fixed everything 😉
Hard to tell from the code you have posted, but I believe you need to make
Client.readInfofieldvolatile. The reason thatThread.Sleepfixed your problem is that it puts a memory barrier as a side effect.