Forum C# Function executes more times than it should

Function executes more times than it should

Postby kustrle » March 21st, 2011, 9:41 pm

In UserJoined function I want to show waiting message if there is only 1 player in the room and init game when the second player joins.
Code: Select all
public override void UserJoined(Player player) {
if (PlayerCount < 2){
player.Send("wait");
}else{
if(!init){
InitGame();
init=true;//init is a private variable, set to false when new game is created
}

However, if 2 users join in the same moment, InitGame function gets executed twice. It's like 2 UserJoined function would get executed simultaneously, causing InitGame to be executed twice too. How to fix that? Thanks.
kustrle
 
Posts: 10
Joined: February 11th, 2011, 10:16 pm

Re: Function executes more times than it should

Postby wildbunny » April 1st, 2011, 9:45 am

This is because player.io is multi-threaded.

You need to do a lock(this) around the message handling function, and inside the timer loop as well...

Cheers, Paul.
wildbunny
 
Posts: 217
Joined: March 9th, 2011, 10:35 am


Return to C#