Deepak Mishra
Deepak Mishra

Reputation: 3183

Why is sometimes async keyword not used with a method suffixed with async?

I was reading about health check in asp.net core.

I have seen this code.

public class ExampleHealthCheck : IHealthCheck
{
    public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default(CancellationToken))
    {
        var healthCheckResultHealthy = true;

        if (healthCheckResultHealthy)
        {
            return Task.FromResult(
                HealthCheckResult.Healthy("A healthy result."));
        }

        return Task.FromResult(
            HealthCheckResult.Unhealthy("An unhealthy result."));
    }
}

In the above code the method CheckHealthAsync is not marked async. Is it made in such a way to support both synchronous and asynchronous function?

Upvotes: 1

Views: 433

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

There are two parts to this answer:

  • Async suffix is used to satisfy IHealthCheck interface requirement. It is just a naming convention (albeit an important one) which has no special meaning in the language itself.
  • async is not used because method's implementation does not need it (i.e. it has no awaits)

Note that the implementation also uses Task.FromResult rather than returning the value directly. This is also done to satisfy the requirements of IHealthCheck interface, which is designed to allow for implementations to be asynchronous.

Upvotes: 6

Patrick Beynio
Patrick Beynio

Reputation: 858

async only allows you to use await, if you're looking for a way to tell if something runs async, a return type of Task is your best hint.

Upvotes: 0

Related Questions