C# error System.NullReferenceException

前端 未结 3 1465
情深已故
情深已故 2021-01-28 17:00

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

相关标签:
3条回答
  • 2021-01-28 17:20

    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... -.-
     }
    
    0 讨论(0)
  • 2021-01-28 17:27

    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");
    });
    
    0 讨论(0)
  • 2021-01-28 17:32

    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.

    0 讨论(0)
提交回复
热议问题