以下是一个示例的解决方案,其中使用了ASP.NET MVC页面来显示进度并在后台运行一些任务。
首先,创建一个名为"Progress"的控制器,如下所示:
using System.Threading;
using System.Web.Mvc;
namespace YourNamespace.Controllers
{
public class ProgressController : Controller
{
private static CancellationTokenSource _cancellationTokenSource;
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Start()
{
// 创建一个新的取消令牌源
_cancellationTokenSource = new CancellationTokenSource();
// 启动后台任务
ThreadPool.QueueUserWorkItem(BackgroundTask, _cancellationTokenSource.Token);
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Stop()
{
// 取消后台任务
_cancellationTokenSource?.Cancel();
return RedirectToAction("Index");
}
private void BackgroundTask(object token)
{
var cancellationToken = (CancellationToken)token;
for (var i = 0; i <= 100; i++)
{
// 检查是否已取消任务
if (cancellationToken.IsCancellationRequested)
{
break;
}
// 模拟一些耗时操作
Thread.Sleep(1000);
// 更新进度
ProgressHub.SendProgress(i);
}
// 任务完成时更新进度为100%
ProgressHub.SendProgress(100);
}
}
}
接下来,创建一个名为"Progress.cshtml"的视图,如下所示:
@{
Layout = null;
}
进度示例
进度示例
0%
最后,创建一个名为"ProgressHub.cs"的Hub类,用于向前端发送进度更新:
using Microsoft.AspNet.SignalR;
namespace YourNamespace.Hubs
{
public class ProgressHub : Hub
{
public static void SendProgress(int progress)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext();
hubContext.Clients.All.updateProgress(progress);
}
}
}
确保已在Global.asax.cs文件中注册SignalR路由:
using System.Web.Mvc;
using System.Web.Routing;
using YourNamespace.Hubs;
namespace YourNamespace
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
// 启动SignalR
GlobalHost.HubPipeline.RequireAuthentication();
RouteTable.Routes.MapHubs();
}
}
}
完成上述步骤后,当您访问"Progress/Index"页面时,您将看到一个进度指示器和"开始"和"停止"按钮。单击"开始"按钮将触发后台任务,并在页面上更新进度,单击"停止"按钮将取消后台任务。