【发布时间】:2019-12-02 06:02:52
【问题描述】:
我在SignalR 部分中有以下Hub 类,在这里我定义了与连接相关的所有方法:
public override Task OnConnected()
{
// here I cannot call this, and need to convert this method async
await AddToGroup("stockGroup");
//
string name = Context.User.Identity.Name;
_connections.Add(name, Context.ConnectionId);
return base.OnConnected();
}
public async Task AddToGroup(string groupName)
{
await Groups.Add(Context.ConnectionId, groupName);
await Clients.Group(groupName).SendAsync("Send", $"{Context.ConnectionId} joined");
}
我查看了许多关于这些连接方法(和其他 Hub 方法)的不同示例,发现其中一些使用 async 方法,而另一些则不使用。在上面的示例中,我需要将 OnConnected() 方法转换为 async 以便调用 AddToGroup() 方法。当然相反的情况也可以,但我不确定哪个更好。那么,对于Hub 中的所有方法,我应该使用async 方法还是非异步方法?任何帮助,将不胜感激。
更新 1: 转换方法(到异步)。
public override async Task OnConnected()
{
await AddToGroup("stockGroup");
string name = Context.User.Identity.Name;
_connections.Add(name, Context.ConnectionId);
return base.OnConnected();
}
更新 2:
public override async Task OnConnected()
{
// #1 There is no async method in "Microsoft.AspNet.SignalR" library.
//await Groups.AddToGroupAsync(Context.ConnectionId, "SignalR Users");
// #2 I just have sync version of "AddToGroupAsync()" and used it
await Groups.Add(Context.ConnectionId, "SignalR Users");
/* #3 I think there is no need to use this custom method in the Hub.
Because the same method is already exist in the IGroupManager interface */
//await AddToGroup("jiraGroup");
string name = Context.User.Identity.Name;
_connections.Add(name, Context.ConnectionId);
// #4 Here also the same problem and I used sync version of OnConnected()
//await base.OnConnectedAsync();
await base.OnConnected();
}
【问题讨论】:
-
听起来有点基于意见......这取决于你需要什么。是否需要等到执行结束?你说'有一些问题我看到集线器中的异步调用有时可能导致无法连接到集线器',什么问题?你的用例中有它们吗?如果发生这种情况,这对您的用例是否至关重要?
-
@nilsK 对不起,你是对的。我变得更干净了。这个问题似乎是基于意见的,但由于这是我第一次使用 SignalR 并且在构建我的 Hub 类时遇到了这个问题,所以我想为一般情况选择最佳选项(你更喜欢 Hub 方法中的什么?异步或同步?)。当然两者都是可能的,但这两种选择的优缺点是什么?在此先感谢...
-
恕我直言,你问错问题了。在您写“因为在网络上存在一些问题我看到
Hub中的async调用可能会导致有时无法连接到集线器。”,您应该询问如何解决这个问题。如果答案是不使用async,那就应该这样。 -
@LGSon 好的,我从我的问题中删除了该部分。我现在可以听听你的意见吗?
-
征求意见是"off-topic"在SO。
标签: c# asp.net-mvc asp.net-core async-await signalr