-2

I have a scenario where I have to call API periodically to receive health status.

what if I use a while use?

 while (true)
  {
// API call
   var health = _client.GetHealth(1).Result;
   if (health)
     {
       some other work

     }
   Thread.Sleep(2000);
  }
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Rabner Casandara
  • 151
  • 3
  • 18
  • In general, sleep loops are rarely a good solution. You might want to take a look at some kind of [timer](https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.timer?view=netframework-4.8) – JonasH Nov 08 '21 at 09:05
  • 2
    First, this is available out of the box with [Health Checks](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-6.0). Second, you can't just create a sleep loop or a timer in a controller. Controller instances are created to serve a single request and will eventually be garbage collected. You need a BackgroundService for long running jobs. Finally, `Thread.Sleep` should never be used in a web application. Use `Task.Delay` at least. – Panagiotis Kanavos Nov 08 '21 at 09:08
  • You could use a [hosted service](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-6.0&tabs=visual-studio), which is available in .net core. – Adrian Nov 08 '21 at 09:09
  • @PanagiotisKanavos I am not calling this API in Controller – Rabner Casandara Nov 08 '21 at 09:35
  • @RabnerCasandara in that case you'll have to explain what you actually want. Where are you calling it? And what is the actual question? Why did you ask if this code is OK? (it's not, don't use .Result) – Panagiotis Kanavos Nov 08 '21 at 09:44
  • Please make your intent clear, do you want to report health of your API/service, or you want a client application to periodically report Healths of multiple services you have hosted? – Code Name Jack Nov 09 '21 at 08:18

2 Answers2

3

This is already available through the Health Checks middleware. The health checks service will check the registered probes periodically to see if everything is OK. The health status can be logged or exposed through an API endpoint.

There are several probes available. The open source AspNetCore.Diagnostics.HealthChecks library offers probes from everything from remote APIs to various database products, cloud services and more. It also offers a Health check dashboard that displays detailed health check history.

Using Health Checks is easy, as it's already included in the web app templates.

Registering it requires adding the following to Startup.cs :

public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks();
}

public void Configure(IApplicationBuilder app)
{
    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHealthChecks("/health");
    });
}

MapHealthChecks exposes a basic status at /health endpoint. To check a remote API you can add the AspNetCore.HealthChecks.Uris package and use one of the AddUrlGroup overloads:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks()
            .AddUrlGroup(new Uri("http://httpbin.org/status/200"));
}
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
0

You can use async programming,

public async Task HealthCheckAsync()
{
 while (true)
  {
// API call
   var health = await _client.GetHealth(1);
   if (health)
     {
       some other work

     }
    await Task.Delay(2000);
  }
}

This works the same way except that it is not blocking the main thread while it waits for the response from server or while it is waiting for next cycle.

Code Name Jack
  • 2,856
  • 24
  • 40
  • This doesn't work for the same reason `Thread.Sleep` doesn't work. Controller actions are only meant for short-lived requests and will be GCd eventually, or throw a timeout. Besides, health checks are built into ASP.NET Core – Panagiotis Kanavos Nov 08 '21 at 09:13
  • I believe he was looking for a health check client. In such cases it works. It doesnt have to be controller action, it can be an independent console app. – Code Name Jack Nov 09 '21 at 08:15