C# error System.NullReferenceException

前端 未结 3 1507
情深已故
情深已故 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: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 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");
    });
    

提交回复
热议问题