C# 错误 System.NullReferenceException [英] C# error System.NullReferenceException

查看:78
本文介绍了C# 错误 System.NullReferenceException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 System.NullReferenceException 有一些问题.当服务器做事时,我们首先检查用户不为空,然后他断开连接,服务器进行一些操作,它尝试让用户出现 System.NullReferenceException.我有超过 20 000 行代码,所以我需要一些小的东西,而不是总是检查它是否为空..如果我把try/catch"放在任何地方,那是好事吗?

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?

示例:

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

推荐答案

看起来 User 的值在测试之后但在调用 SendMessage 之前发生了变化.如果您的应用程序是多线程的,我怀疑另一个线程在您睡觉时将 User 设置为 null.

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.

一种选择是获取 User 并检查它:

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
}

这样您就可以确保您获得了有效的参考.您现在需要做的是确保 user 处于有效状态以便您调用 SendMessage.

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.

更新:由于您一直避免添加 try/catch 块,您可以编写一个辅助函数:

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

现在你可以说:

WithUser(user=>
{
  System.Threading.Thread.Sleep(1000);
  user.SendMessage("crash");
});

这篇关于C# 错误 System.NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆