I've declared a System.Timers.Timer inside an Api Controller.
Next there is an Action that gets called by a Javascript client and its task is to make every second an HTTP GET request to an external server which sends back a JSON.
Then the JSON gets sent to the Javascript client via WebSocket.
Also I've created another Action that stops the timer when being called.
[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
{
// ...
}
}
// ...
}
The problem is, since ASP.NET Controllers (so .Net Core ones?) gets instancieted for every new request, when I call the Stop timer method, the timer doesn't stop because it's not the right Timer instance. So the system continues to make HTTP requests and Websocket transfers...
Is there a way to save and work on the Timer instance I need to stop from a different Controller instance or can I retrieve the original Controller instance?
Thanks in advance guys :)