1

I want to monitor CPU performance on my ASP.NET MVC5 application and users are able to select the PC they want to be monitored. I use SignalR for monitoring real time CPU performance. It works well for first CPU, the problem is once user select another PC to be monitored, another new Task according to this link will be created so that both of the previous and new Task will sent their data to the client chart.

What is the solution for handling my problem so that once user change the PC just corresponding PC's data will send to the client side chat or maybe I need to change my code so that just the first current Task can keep sending data.

I really appreciate any help.

Here is my code which is called every time user select any PC :

public class MonitorHub : Hub
{
    CancellationTokenSource wtoken;
    public MonitorHub()
    {
        wtoken = new CancellationTokenSource();
    }

    public void StartCounterCollection(string pcName)
    {
        var unitOfWork = new CMS.Data.UnitOfWork();
        var task = Task.Factory.StartNew(async () =>
        {

            var perfService = new PerfCounterService();
            // await FooAsync(perfService, ref pcName);
            while (true)
            {

                var result = perfService.GetResult(pcName);
                Clients.All.newCounter(result);
                await Task.Delay(2000, wtoken.Token);

            }
        }
        , wtoken.Token);

    }
Ali
  • 103
  • 2
  • 11

1 Answers1

2

You need to work with Groups and Server Broadcast.

Client: when the the PC is changed, leave the existing PC group "pcName1" and join the selected PC group "pcName2".

Server: First, try Working with Groups in SignalR to implement the groups. After that, use the Server Broadcast to broadcast to each group from the server with:

var clients = GlobalHost.ConnectionManager.GetHubContext<MonitorHub>().Clients;
clients.Group("pcName1").updateValues(values)

Later Edit

Tasks use background threads from the thread pool. Canceling threads using the Abort method is not recommended.

In order to update your chart every few seconds using SignalR, you have two options:

  1. Use SetInterval() in your javascript to call your hub and get the values every few seconds. Don't start any tasks, just return the values. This way, when the client disconnects or changes the PC, you won't have to abort any running tasks.

  2. Server broadcast from a job that is not created in the hub

    • keep track of the groups with connected clients (using JoinGroup() and LeaveGroup())
    • in the background job, for each group(PC), get the values and broadcast them to connected clients

Useful links:

Community
  • 1
  • 1
Florin Secal
  • 931
  • 5
  • 15