I have some problems with System.NullReferenceException. When server do things and we first check user is not null and then he disconnect and server progress something and it tr
SendMessage
is throwing null exception, check code in your SendMessage
Method
if User
goes null before call dont call SendMessage:-
if (User != null)
{
User.SendMessage("crash"); //<-- No More System.NullReferenceException... -.-
}
It looks like the value of User
is changing after the test but before the call to SendMessage
. If your application is multithreaded I suspect that another thread is setting User
to null whilst you are sleeping.
One option would be to grab User
and check against it:
var user = User;
if (user != null)
{
//do some things
System.Threading.Thread.Sleep(1000);get error)
user.SendMessage("crash"); // Need to be sure user is in a valid state to make call
}
This way you can be sure that you've got a valid reference. What you'll now need to do is ensure that user
is in a valid state for you to call SendMessage
.
UPDATE: Since you're keep to avoid adding try/catch blocks you could write a helper function:
void WithUser(Action<User> action)
{
try
{
var user = User;
if (user != null) action(user);
}
catch(Exception e)
{
// Log it...
}
}
Now you can say:
WithUser(user=>
{
System.Threading.Thread.Sleep(1000);
user.SendMessage("crash");
});
Who is setting User
to null and where? While your thread sleeps, somebody is obviously setting the User variable to null, causing the crash.
Besides: "Magical sleeps" will not solve any problems. You need proper locking here.