Câu hỏi phỏng vấn .NET Core
Câu hỏi

What is the correct pattern to implement long running background work in Asp.Net Core?

Câu trả lời

To implement long-running background work in ASP.NET Core, the recommended pattern is to use hosted services. Hosted services are classes that implement the IHostedService interface, which provides methods for starting and stopping background tasks. This approach ensures that the background tasks are managed by the ASP.NET Core runtime, allowing for proper initialization, execution, and graceful shutdown of these tasks.

Key Concepts and Implementation

  1. IHostedService Interface:
    The IHostedService interface defines two methods:

    • StartAsync(CancellationToken cancellationToken): This method contains the logic to start the background task and is called when the application starts.
    • StopAsync(CancellationToken cancellationToken): This method contains the logic to stop the background task and is called when the application is shutting down.
  2. BackgroundService Class:
    ASP.NET Core provides an abstract BackgroundService class that implements IHostedService and provides a convenient way to create long-running background tasks. You only need to override the ExecuteAsync method to define the background task logic.

  3. Dependency Injection:
    Background services can use dependency injection to access other services within the application. However, only transient or singleton services can be directly injected into the constructor of a hosted service. Scoped services must be resolved within the ExecuteAsync method using a service scope.

Example Implementation

Here is an example of implementing a background service using the BackgroundService class:

csharp Copy
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

public class ExampleBackgroundService : BackgroundService
{
    private readonly IServiceProvider _serviceProvider;
    private readonly ILogger<ExampleBackgroundService> _logger;

    public ExampleBackgroundService(IServiceProvider serviceProvider, ILogger<ExampleBackgroundService> logger)
    {
        _serviceProvider = serviceProvider;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Background service is starting.");

        while (!stoppingToken.IsCancellationRequested)
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
                // Perform your background task here
                await dbContext.SomeLongRunningTaskAsync(stoppingToken);
            }

            _logger.LogInformation("Background service is running.");
            await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
        }

        _logger.LogInformation("Background service is stopping.");
    }
}

Registering the Background Service

To register the background service, add it to the service collection in the Program.cs or Startup.cs file:

csharp Copy
public class Program
{
    public static void Main(string[] args)
    {
...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What about MVC in .NET Core?

senior

Explain Implicit Compilation process

junior

What is Generic Host in .NET Core?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào