SignalR - Send message OnConnected

后端 未结 4 1644
半阙折子戏
半阙折子戏 2021-02-14 02:15

I\'ve been experimenting with SignalR today and It\'s really neat. Basically what I wanted to achieve is the following:

As soon as a device connects it should send a mes

4条回答
  •  -上瘾入骨i
    2021-02-14 02:55

    well... you are returning a task... so i think that may be the issue... you should first execute your code and then return the task... or put a ContinueWith... like...

        public override Task OnConnected()
        {
            Task task = new Task(() =>
                {
                    UserHandler.ConnectedIds.Add(Context.ConnectionId, UserHandler.ConnectedIds.Count + 1);
    
                    int amountOfConnections = UserHandler.ConnectedIds.Count;
                    var lastConnection = UserHandler.ConnectedIds.OrderBy(x => x.Value).LastOrDefault();
                    var allExceptLast = UserHandler.ConnectedIds.Take(amountOfConnections - 1).Select(x => x.Key).ToList();
    
                    if (amountOfConnections == 1)
                    {
                        Clients.Client(UserHandler.ConnectedIds.First().Key).hello("Send to only(also first) one");
                    }
                    else
                    {
                        Clients.Clients(allExceptLast).hello("Send to everyone except last");
                        Clients.Client(lastConnection.Key).hello("Send to only the last one");
                    }
                });
    
            task.ContinueWith(base.OnConnected());
    
            return task;
        }
    

    I haven't tested that... its just a guess..

提交回复
热议问题