I have a long running process that I would like to add a REST api to. Through the API I would like to be able to inspect the values of variables inside the long running process.
I put together a proof of concept using minimal API:
public class Program
{
public static int val = 0;
public static object locker = new object();
public static void Main(string[] args)
{
Task.Run(() =>
{
while (true)
{
lock (locker)
{
val++;
}
Thread.Sleep(100);
}
});
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () =>
{
lock (locker)
return val;
});
app.Run();
}
}
My idea is to have the code for my long running process running inside of the Task.Run. Am I going about this the right way? Are there any potential pitfalls/gotchas to what Im trying to do?
You could create a service that holds the state, and you can access that service from your API. A windows service/hosted service is great for a "long-running process", and it can host your API: documentation.
ValueService.cs
Implement
BackgroundService
for your long running process.Program.cs
Register your service and register retrieval from the service provider.
Inject service in your API: