【发布时间】:2020-11-17 05:08:03
【问题描述】:
我对空引用异常有疑问,不明白为什么会发生这种情况。这是我的中心
public class UserHub : Hub
{
private static List<Connection> Users = new List<Connection>();
public override async Task OnConnected()
{
string id = Context.ConnectionId;
string userName = Context.User.Identity.Name;
if (Users == null)
Users = new List<Connection>();
if (!Users.ToArray().Any(_ => _.UserName == userName))
Clients.AllExcept(Context.ConnectionId).onNewUserConnected(id, userName);
if (!Users.ToArray().Any(x => x.ConnectionId == Context.ConnectionId))
Users.Add(new Connection { ConnectionId = id, UserName = userName });
Clients.Caller.onConnected(id, userName, Users.DistinctBy(_ => _.UserName).ToList());
await base.OnConnected();
}
public override async Task OnReconnected()
{
string id = Context.ConnectionId;
string userName = Context.User.Identity.Name;
if (Users == null)
Users = new List<Connection>();
if (!Users.Any(_ => _.UserName == userName))
Clients.AllExcept(Context.ConnectionId).onNewUserConnected(id, userName);
if (!Users.Any(x => x.ConnectionId == id))
Users.Add(new Connection { ConnectionId = id, UserName = userName });
Clients.Caller.onConnected(id, userName, Users.DistinctBy(_ => _.UserName).ToList());
await base.OnReconnected();
}
public override async Task OnDisconnected(bool stopCalled)
{
if (Users == null)
Users = new List<Connection>();
var item = Users.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId);
if (item != null)
Users.Remove(item);
Clients.All.onUserDisconnected(Context.ConnectionId, item.UserName);
await base.OnDisconnected(stopCalled);
}
}
问题出现在 onConnected 方法中,在这一行:
if (!Users.ToArray().Any(_ => _.UserName == userName))
我尝试在上面添加对 null 的检查,但它不起作用。怎么了?该问题随机出现。
堆栈跟踪:
at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
at App.Web.Hubs.UserHub.<OnConnected>d__1.MoveNext() in E:\Company\App\App\Presentation\App.Web\Hubs\UserHub.cs:line 49
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
...
【问题讨论】:
-
那么 is 究竟是什么?用户?列表中的条目?你有堆栈跟踪吗?
-
我相信如果列表中的条目为 null 并且用户有错,那没关系。我已将堆栈跟踪添加到初始消息
-
好吧,看来
_在您的列表中为空。 -
怎么回事,我没有在 Users 数组中添加空值?
标签: c# asp.net-web-api signalr signalr-hub