C# error System.NullReferenceException

≡放荡痞女 提交于 2019-12-04 06:12:40

问题


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

回答1:


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");
});



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/21929016/c-sharp-error-system-nullreferenceexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!