【发布时间】:2020-08-18 12:32:29
【问题描述】:
我在 Api 控制器中声明了一个 System.Timers.Timer。
接下来有一个被 Javascript 客户端调用的 Action,它的任务是每秒向外部服务器发送一个 HTTP GET 请求,该请求发回一个 JSON。
然后 JSON 通过 WebSocket 发送到 Javascript 客户端。
我还创建了另一个在被调用时停止计时器的操作。
[Route("api")]
[ApiController]
public class PositionController : ControllerBase
{
private System.Timers.Timer aTimer = new System.Timers.Timer();
// ...
// GET api/position/state
[HttpGet("[controller]/[action]")]
public async Task<string> StateAsync()
{
try
{
Console.WriteLine("In StateAsync (GET)");
string json = "timer started";
aTimer.Elapsed += new ElapsedEventHandler(async (sender, args) =>
{
json = await Networking.SendGetRequestAsync("www.example.com");
Console.WriteLine($"Json in response:");
Console.WriteLine(json);
await _hubContext.Clients.All.SendAsync("ReceiveMessage", json);
});
aTimer.Interval = 1000;
aTimer.Enabled = true;
Console.WriteLine("----------------------------------");
return json;
}
catch (HttpRequestException error) // Connection problems
{
// ...
}
}
// GET api/position/stopstate
[HttpGet("[controller]/[action]")]
public async Task<string> StopStateAsync()
{
try
{
Console.WriteLine("In StopStateAsync (GET)");
string json = "timer stopped";
aTimer.Enabled = false;
Console.WriteLine("----------------------------------");
return json;
}
catch (HttpRequestException error) // Connection problems
{
// ...
}
}
// ...
}
问题是,由于 ASP.NET 控制器(所以是 .Net Core 的?)gets instancieted for every new request,当我调用 Stop timer 方法时,计时器不会停止,因为它不是正确的 Timer 实例。于是系统继续发出HTTP请求和Websocket传输……
有没有办法保存和处理 Timer 实例,我需要从不同的 Controller 实例停止,或者我可以检索原始 Controller 实例吗?
提前谢谢大家:)
【问题讨论】:
-
制作
Timer属性static -
您可能最好有一个存储库(在内存中(单实例)或数据库中),您可以在其中存储这些与时间相关的项目。启动计时器时,它应该创建某种唯一标识符,该标识符由 StateAsync 操作返回,并在调用时传递给 StopStateAsync 操作。然后,您可以根据引用标识符查找正确的实例。另外,我宁愿不使用计时器,而只使用带有“开始”和“结束”时间戳的 POCO 对象。您没有取消订阅计时器事件,这不是一个好习惯。
标签: c# asp.net-core .net-core asp.net-core-webapi