NetCoreUsefullEndpoints-part 10- adding LongRunningTasks

In the Nuget NetCoreUsefullEndpoints I have already an  endpoint to shutdown  –  see http://msprogrammer.serviciipeweb.ro/2023/02/20/netcoreusefullendpoints-part-9-adding-endpoints-for-shutdown/ .

However, this means that there are no ( or some … )  long running operations that are running … How to identify those ?

For the starting point , I was thinking at something simple, like an IDisposable that knows when the Long Running operation is finished

[HttpGet(Name = “GetWeatherForecast”)]
         public async Task<WeatherForecast[]> Get()
         {
             using var lr = UsefullExtensions.UsefullExtensions.AddLRTS(“weather”+DateTime.UtcNow.Ticks);
             await Task.Delay(5000);
             return Enumerable.Range(1, 5).Select(index => new WeatherForecast
             {
                 Date = DateTime.Now.AddDays(index),
                 TemperatureC = Random.Shared.Next(-20, 55),
                 Summary = Summaries[Random.Shared.Next(Summaries.Length)]
             })
             .ToArray();
         }

The implementation is very simple for adding:

internal static Dictionary<string, LongRunningTask> lrts = new();
public static LongRunningTask AddLRTS(string id, string? name = null)
{
     if(lrts.ContainsKey(id))
     {
         lrts[id].Dispose();
     }
     lrts.Add(id,new LongRunningTask(id, name ?? id));
     return lrts[id];
}

And for removing itself:

public record LongRunningTask(string id, string? name = “”) : IDisposable
{
     public void Dispose()
     {
         UsefullExtensions.lrts.Remove(id);
         GC.SuppressFinalize(this);
     }

}

Also, an endpoint will be registered for the user know what are the operations

var rh = route.MapGet(“api/usefull/LongRunningTasks/”,
             (HttpContext httpContext) =>
             {
                 var data=lrts.Select(it=>new { it.Key, it.Value.name }).ToArray();
                 return data;
             });

        var rhCount = route.MapGet(“api/usefull/LongRunningTasks/Count”,
             (HttpContext httpContext) =>
             {
                 return lrts.LongCount();
             });

And that will be to register and found what are the long running tasks in ASP.NET Core