使用SignalR和IProgress接口进度报告 [英] Progress report using SignalR and IProgress interface
问题描述
我有一个集线器类,它有一个长期运行的方法,我需要显示一个进度条,而它的工作。
I have a Hub class, which has a long running method, I need to display a progress bar while it's working.
我看了 ,我认为这是可能使用异步方法IProgress接口发送长时间运行的工作状态。
I read this article and I think it is possible to use IProgress interface in async methods to send long running operation status.
我写这样的方法:
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 try to invoke the method like this:
var appHub = $.connection.appHub;
$.connection.hub.start();
appHub.server.getServerTime()
.done(function (time) {
alert(time);
});
但我不知道我怎么能得到进展报告。
But I don't know how can I get the progress reports.
推荐答案
您可以使用进步
,因为这样的:
You can use progress
, 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
在服务器端的CPU绑定code没有意义的。你的服务器端code可以很容易的是:
On a side note, there's no point in using Task.Run
over CPU-bound code on the server side. Your server-side code could just as easily be:
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();
}
您的服务器端方法只应异步
如果他们有真正的异步工作要做(通常是I / O绑定操作)。作为一般规则,避免 Task.Run
服务器端。
Your server-side methods should only be async
if they have true asynchronous work to do (usually I/O-bound operations). As a general rule, avoid Task.Run
on the server side.
这篇关于使用SignalR和IProgress接口进度报告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!