與ASP.NET SignalR和Bootstrap監控服務器任務
上TaskController冗長的方法是經典的,時間可能很長,任務可能需要一段時間才能完成,爲此通知到客戶端對用戶來說是合適和方便的。爲了演示,下面是一些虛擬代碼,它們模擬了典型業務工作流程的逐步執行。
public class TaskController : Controller
{ public void Lengthy([Bind(Prefix="id")] string taskId)
{
ProgressHub.NotifyStart(taskId);
// A bit of work
Thread.Sleep(2000);
ProgressHub.NotifyProgress(taskId, 20);
// A bit of work
Thread.Sleep(1000);
ProgressHub.NotifyProgress(taskId, 30);
// A bit of work
Thread.Sleep(2000);
ProgressHub.NotifyProgress(taskId, 50);
Thread.Sleep(3000);
ProgressHub.NotifyProgress(taskId, 80);
// A bit of work
Thread.Sleep(1000);
ProgressHub.NotifyProgress(taskId, 90);
// Final piece of work
Thread.Sleep(1000);
ProgressHub.NotifyEnd(taskId);
}
}
正如您所看到的,該任務通過多個步驟進行了闡述,每個步驟都表示完成了大量工作。爲了讓事情儘可能通用,我設想了一個由三種方法組成的編程API:NotifyStart,NotifyProgress和NotifyEnd。所有這些方法都必須在ASP.NET SignalR集線器類中定義。這是hub類的一個可能的實現。
public class ProgressHub : Hub
{
public void NotifyStart(string taskId)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();
hubContext.Clients.All.initProgressBar(taskId);
}
public void NotifyProgress(string taskId, int percentage)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();
hubContext.Clients.All.updateProgressBar(taskId, percentage);
}
public void NotifyEnd(string taskId)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();
hubContext.Clients.All.clearProgressBar(taskId);
}
}
你看過http://stackoverflow.com/questions/26366590/angular-show-loading-when-any-resource-is-in-pending? – RQDQ
@RQDQ我的問題不在角度部分我的問題是如何在後臺運行代碼 –