Home > other >  Shutdown of IHostedService
Shutdown of IHostedService

Time:10-10

I am trying to develop an asynchronous, multi-threaded .NET Core console app, but after implementing the code from the tutorial once starts to implement this, the code is shut down

Microsoft.Hosting.Lifetime: Information: application is shutting down

Started to write a method to execute using asynchronous, multi-threaded

private async Task<List<RegistrationData>> ProcessPendingRegistrationsAsync(List<RegistrationData>  registrations)
{
    return registrations;
}

and then I run this method using "Task.Run"

foreach (var openPendingRegistrationsData in openPendingRegistrationsPerPages)
    processPendingRegistrationsTasks.Add(Task.Run(() => ProcessPendingRegistrationsAsync(openPendingRegistrationsData)
);

and finally, I want to await all tasks using await Task.WhenAll():

if (processPendingRegistrationsTasks.Count > 0)
{
    await Task.WhenAll(processPendingRegistrationsTasks);
}

Console.WriteLine("Finish running code");

To more clear the code didn't print the message in Console.WriteLine, once I implement Task.WhenAll.

Please, can anyone let me know what the problem is?

EDIT

Program.cs

internal class Program
{
    private static void Main(string[] args)
    {
        var log4NetConfiguration = new Log4NetConfiguration();
        log4NetConfiguration.SetLog4NetConfiguration();
        var host = CreateHostDefaultBuilder(args).Build();
        host.RunAsync();
        RunTask(host.Services);
    }

    public static IHostBuilder CreateHostDefaultBuilder(string[] args)
    {
        return Host.CreateDefaultBuilder()
            .ConfigureAppConfiguration(app => { app.AddJsonFile("appsettings.json"); })
            .ConfigureServices((_, services) =>
            {
                services.ConfigureDAL().ConfigureBusiness().ConfigureConnectionHelper().ConfigureTimeOutSetting();
            });
    }

    public static void RunTask(IServiceProvider services)
    {
        var taskHelper = (TaskHelper)services.GetService(typeof(TaskHelper));
        taskHelper?.Execute(true);
    }
}

TaskHelper.cs

public async Task Execute(bool forceMode)
{
    var openPendingRegistrationsPerPages =
            _dRegistration.GetAllRegistrationsByStatusAndSubStatusPerPage(cachedByGuid[1], cachedByGuid[2]);

    foreach (var openPendingRegistrationsData in openPendingRegistrationsPerPages)
        processPendingRegistrationsTasks.Add(Task.Run(() => ProcessPendingRegistrationsAsync(openPendingRegistrationsData));
}

if (processPendingRegistrationsTasks.Count > 0)
{
    await Task.WhenAll(processPendingRegistrationsTasks);
}

Console.WriteLine("Finish running code");


private async Task<List<RegistrationData>> ProcessPendingRegistrationsAsync(List<RegistrationData>  registrations)
{
    // Process
    return registrations;
}

CodePudding user response:

You're not waiting for taskHelper.Execute(true) to finish executing.

The issue stems from your RunTask(...) method:

public static void RunTask(IServiceProvider services)
{
  var taskHelper = (TaskHelper)services.GetService(typeof(TaskHelper));
  taskHelper?.Execute(true);
}

.Execute returns a Task:

public async Task Execute(bool forceMode)

Unless you await this call which you can't since RunTask is not an async method, your code will not wait for the Task returned by the method to finish running.

In this case, the simple solution would be to use the Task.Wait method to wait for the Task to complete execution.

This should work:

public static void RunTask(IServiceProvider services)
{
  var taskHelper = (TaskHelper)services.GetService(typeof(TaskHelper));
  taskHelper?.Execute(true).Wait();
}
  • Related