JQuery example for calling SignalR Async Task

2019-09-12 17:18发布

问题:

Does anyone have a working example of a JQuery based client calling an async task based method on a SignalR Hub? See the code below from the SignalR Doco for an example of a server side async task.

public Task<int> AsyncWork() 
    {
        return Task.Factory.StartNew(() => 
        {
            // Don't do this in the real world
            Thread.Sleep(500);
            return 10;
        });
    }

回答1:

Here is an example *at server side:*

public void  AsyncWork() 
    {

          // start working in a new thread
          var task = Task.Factory.StartNew(() => dosomething());

    task.ContinueWith(t =>
                                  {
                                      Caller.notifyResult(t.Result);
                          });

    }


   private int dosomething()
        {
            int result =0;
            return result;
        }

At client side:

<script type="text/javascript">
// init hub 
var proxy = $.connection.signals;

// declare response handler functions, the server calls these
proxy.notifyResult = function (result) {
    alert("the result was: " + result);
};

// start the connection
$.connection.hub.start();

// Function for the client to call
function AsyncWork() {
    proxy.AsyncWork(); 
}
</script>