简体   繁体   English

使用Signalr中的异步服务器到客户端消息

[英]server to client message using async in signalr

currently i'm using this code to send to each client a slightly different message. 目前,我正在使用此代码向每个客户端发送略有不同的消息。 When there are 100+ clients, this same code without task is blocking my timer loop, and i suspect it to also block all web requests. 当有100多个客户端时,没有任务的同一代码将阻止我的计时器循环,我怀疑它也将阻止所有Web请求。

ConcurrentDictionary Sessions;
// ...


var context = GlobalHost.ConnectionManager.GetHubContext<TiHub>();
foreach(var kp in Sessions) 
{
    var client = context.Clients.Client(kp.Key);
    if (client != null)
     {
          client.changed(new Data{ data=somevalue(kp.Value) });
     }
}

Async version 异步版本

        var context = GlobalHost.ConnectionManager.GetHubContext<TiHub>();

        return Task.Run(() =>
        {
            Parallel.ForEach(Sessions, kp =>
            {
                var client = context.Clients.Client(kp.Key);
                if (client != null)
                {
                    client.changed(new Data{ data=somevalue(kp.Value) });
                }
            });

        });

I would like a task or async version of "changed". 我想要“更改”的任务或异步版本。 Something like: 就像是:

client.changedAsync(new Data{ data=somevalue(kp.Value) });

Is this supported in SignalR ? SignalR是否支持此功能?

Is client.changed I/O bound or CPU bound? client.changed I / O绑定还是CPU绑定?

I suppose it's I/O bound and you'll benefit from async-await . 我想这是I / O绑定的,您将从async-await受益。

Instead of the Parallel.ForEach you might try something like this: 您可以尝试使用以下方法来代替Parallel.ForEach

var context = GlobalHost.ConnectionManager.GetHubContext<TiHub>();
var tasks = (from kp in Sessions
             let client = context.Clients.Client(kp.Key)
             where client != null
             select Task.Run(() =>
                 {
                     client.changed(new Data{ data = somevaluekp.Value);
                 })).ToArray();

await Task.WhenAll(tasks);

But you should try to use natural async-await APIs instead of the artificial Task.Run`. 但是,您应该尝试使用自然的async-await API,而不要使用人工的Task.Run`。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM