Progress Report Using SignalR and IProgress

I have a Hub class that has a long running method, I need to display a progress bar while I work.

I read this article and I think that you can use the IProgress interface in asynchronous methods to send a long working state.

I am writing a method like this:

    public async Task<string> GetServerTime(IProgress<int> prog)
    {
        await Task.Run(() => {
            for (int i = 0; i < 10; i++)
            {
                prog.Report(i * 10);
                System.Threading.Thread.Sleep(200);
            }
        });

        return DateTime.Now.ToString();
    }

And I am trying to call the method as follows:

 var appHub = $.connection.appHub;
 $.connection.hub.start();
 appHub.server.getServerTime()
              .done(function (time) {
                    alert(time);
               });

But I do not know how I can get progress reports.

+4
source share
2 answers

You can useprogress as such:

var appHub = $.connection.appHub;
$.connection.hub.start().done(function() {
  appHub.server.getServerTime()
    .progress(function (update) { alert(update); })
    .done(function (time) { alert(time); });
});

Task.Run . :

public string GetServerTime(IProgress<int> prog)
{
    for (int i = 0; i < 10; i++)
    {
        prog.Report(i * 10);
        System.Threading.Thread.Sleep(200);
    }

    return DateTime.Now.ToString();
}

async, ( I/O). , Task.Run .

+9

javascript

 var appHub = $.connection.appHub;
  $.connection.hub.start();
  appHub.client.progress = function(progresspct) {
     // logic for whatever you want to do.
  };

  appHub.server.getServerTime()
          .done(function (time) {
                alert(time);
           });

, -

    public async Task<string> GetServerTime(IProgress<int> prog)
   {
    await Task.Run(() => {
        for (int i = 0; i < 10; i++)
        {
            prog.Report(i * 10);
            // Call to your client side method.
            Clients.Client(Context.ConnectionId).progress(i);
            System.Threading.Thread.Sleep(200);
        }
    });

    return DateTime.Now.ToString();
}
0

All Articles