I have a SignalR hub to send group notification, I want to test SignalR Groups. Below is the Hub server code :
[HubName("MyHubServer")]
public class HubServer : Hub
{
public override Task OnConnected()
{
// My code OnConnected
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
// My code OnDisconnected
return base.OnDisconnected(stopCalled);
}
public string JoinGroup(string connectionId, string groupName)
{
Groups.Add(connectionId, groupName).Wait();
return connectionId + " joined " + groupName;
}
public string LeaveGroup(string connectionId, string groupName)
{
Groups.Remove(connectionId, groupName).Wait();
return connectionId + " removed " + groupName;
}
public string LeaveGroup(string connectionId, string groupName, string customerId = "0")
{
Groups.Remove(connectionId, customerId).Wait();
return connectionId + " removed " + groupName;
}
}
Server Code to send message to Group (I'll call this code to send message to group after joining group) :
Hub.Clients.Group("Associate").BroadcastAssociateNotification(JsonConvert.SerializeObject(notifications));
Now I want to test SignalR server Group to join group and receive message as server sends message to that group. Below is the code I'm using to test the same, with this code I'm getting error as "A task was canceled" at line Groups.Add(connectionId, groupName).Wait();
static void Main(string[] args)
{
MainAsync().Wait();
Console.ReadLine();
}
static async Task MainAsync()
{
try
{
var hubConnection = new HubConnection("http://localhost:12923/");
IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("MyHubServer");
stockTickerHubProxy.On<string>("Associate", data => Console.WriteLine("Notification received : ", data));
hubConnection.Start().Wait();
await stockTickerHubProxy.Invoke("JoinGroup", "123456", "Associate");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
.Wait
) which can lead to deadlocks within the method. You should await and not block on it. - Nkosi