Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why IHostedService is async

I know this is a design question but I am trying to understand this to use it the best way. So consider this question as clarification of how it could be used with its most capabilities.

Why it is not designed KISS-based synchronized and have async methods (StartAsync, StopAsync), AFAIK, the main benefit of Async in web request is to let some idle threads be released to be used to serve further request but it can't be the case for IHostedService as there is no concept of request and there is always one running (or suspended) thread.

like image 212
mehran Avatar asked Mar 15 '18 22:03

mehran


People also ask

Why API methods are async?

In the context of Web API, Asynchronous programming is used to improve the scalability of the application. By applying asynchronous programming using async and await there won't be any direct performance gain in speed instead application will be able to handle more concurrent requests.

Why we use async in asp net core?

Asynchronous programming allows you to write programs that don't block on each statement or instruction, meaning the computer can move on to other tasks before waiting for previous tasks to finish. As a result, asynchronous programming enables you to build applications that are more scalable and responsive.

What is the point of async?

Note: The purpose of async / await is to simplify the syntax necessary to consume promise-based APIs. The behavior of async / await is similar to combining generators and promises. Async functions always return a promise.

What is the benefit of using async?

with async / await , you write less code and your code will be more maintainable than using the previous asynchronous programming methods such as using plain tasks. async / await is the newer replacement to BackgroundWorker , which has been used on windows forms desktop applications.

What is startasync and stopasync methods in ihostedservice?

IHostedService as Interface. It defines two methods which are StartAsync (CancellationToken) and StopAsync (CancellationToken). StartAsync is nothing but a trigger when the application host to ready to start the service. It contains the logic to start background tasks.

How to implement the ihostedservice and iasyncdisposable interfaces?

Implement the IHostedService, and IAsyncDisposable interfaces. Create a timer-based service. Register the custom implementation with dependency injection and logging. All of the "Workers in .NET" example source code is available in the Samples Browser for download.

What is the use of ihostedservice?

IHostedService allows you to create a async tasks with start and stop actions. It's lifetime is owned by the IHost but the handling of the start and stop actions is up to the hosted service and developer.

What is the difference between ihostedservice and widows service?

In technical terms, any reference type object which implements the IHostedService interface is a background/hosted/worker service. Terms such as Worker, Windows Service, and Background Task refer to HostedService based on context. In Windows Server, Widows Service is how you deploy a Hosted Service.


1 Answers

Let's go down the rabbit hole.

Instances of IHostedService are called by HostedServiceExecutor.StartAsync() which is asynchronous (HostedServiceExecutor source code).

HostedServiceExecutor.StartAsync() is called by WebHost.StartAsync() which is asynchronous (WebHost source code).

WebHost implements IWebHost which has both synchronous and asynchronous versions for start: Start and StartAsync. However WebHost.Start() implementation just calls asynchronous version:

public void Start()
{
    StartAsync().GetAwaiter().GetResult();
}

Finally WebHost.Start() is called by Program.Main (as generated by default ASP.NET Core project template):

public static void Main(string[] args)
{
    BuildWebHost(args).Run();
}

Having this calls chain, we could go on with your question "Why IHostedService is async?" and get "Why IWebHost is async?" or "Why c# 7 introduced async Main() method?".

You could get reasoning for this from the following discussions:

  • What is the point of having async Main?
  • Proposal: Add Async support for Main() / Console Apps
  • C# 7 Series, Part 2: Async Main

Well, the main reason is to simplify calls to async methods from program root. Usually the program flow requires calls to async methods (either your own implementation or 3rd party library). With old approach we were to do something like this:

public static void Main(string[] args)
{
    SomeAsyncCall().GetAwaiter().GetResult();
}

But now we could have it async all the way in a clean way:

static async Task Main(string[] args)
{
    await SomeAsyncCall();
}

The same applies for IHostedService.StartAsync(). It could require calling some async operations during the host service preparation. This discussion of host services concept has an explicit statement about this:

The StartAsync method is asynchronous because we may need to execute some preparation tasks for the job that may fail to execute and compromise the initialization.

Hope this answers your question.

If you are looking for docs about proper implementation of IHostedService, here is a good one: Implementing IHostedService in ASP.NET Core 2.0

like image 70
CodeFuller Avatar answered Sep 27 '22 21:09

CodeFuller