【发布时间】:2016-03-30 07:33:40
【问题描述】:
我正在开发 ASP.NET5 应用程序,我想在一定延迟后触发服务器上的事件。我还希望客户端能够向服务器发送请求以取消事件的执行。
如何持久化Timer,以便在另一个请求中通过调用Change(Timeout.Infinite, Timeout.Infinite) 取消它?
public class ApiController : Controller
{
public IActionResult SetTimer()
{
TimerCallback callback = new TimerCallback(EventToRaise);
Timer t = new Timer(callback, null, 10000, Timeout.Infinite);
//I need to persist Timer instance somehow in order to cancel the event later
return HttpOkObjectResult(timerId);
}
public IActionResult CancelTimer(int timerId)
{
/*
here I want to get the timer instance
and call Change(Timeout.Infinite, Timeout.Infinite)
in order to cancel the event
*/
return HttpOkResult();
}
private void EventToRaise(object obj)
{
///..
}
}
我正在使用 System.Threading.Timer 来延迟 EventToRaise 的执行,我的方法是正确的还是应该以其他方式进行?实现它的最佳方法是什么?
【问题讨论】:
-
@CodeNotFound,谢谢先生,我想我会按照文章中的建议使用Hangfire。
标签: asp.net asp.net-mvc timer