简体   繁体   中英

C# error System.NullReferenceException

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 try get user comes System.NullReferenceException. I have over 20 000 lines code so i need something small not like allways check is it null.. My server is multithread so sockets get connections and disconnects users alltime on backround so thats why this comes.. I want stop that progress when user disconnect. If i put everywhere "try/catch" is that goodway?

Example:

if (User != null)
{
    //do some things
    System.Threading.Thread.Sleep(1000); //now we have time disconnect (This only for get error)
    User.SendMessage("crash"); //<-- 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");
});

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... -.-
 }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM