JQuery example for calling SignalR Async Task

2019-09-12 17:28发布

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条回答
时光不老,我们不散
2楼-- · 2019-09-12 17:35

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>
查看更多
登录 后发表回答