« Background task » : différence entre les versions

De Banane Atomic
Aller à la navigationAller à la recherche
 
(6 versions intermédiaires par le même utilisateur non affichées)
Ligne 11 : Ligne 11 :
     protected override async Task ExecuteAsync(CancellationToken stoppingToken)
     protected override async Task ExecuteAsync(CancellationToken stoppingToken)
     {
     {
         using (var scope = Services.CreateScope())
         using var scope = services.CreateScope();
         {
         var scopedService = scope.ServiceProvider.GetRequiredService<IMyScopedService>();
            var scopedService = scope.ServiceProvider.GetRequiredService<IMyScopedService>();
        await scopedService.DoWork(stoppingToken);
            await scopedService.DoWork(stoppingToken);
        }
     }
     }


Ligne 26 : Ligne 24 :


<filebox fn='Program.cs'>
<filebox fn='Program.cs'>
services.AddHostedService<MyBackgroundService>();
builder.Services.AddHostedService<MyBackgroundService>();
services.AddScoped<IMyScopedService, MyScopedService>();
builder.Services.AddScoped<IMyScopedService, MyScopedService>();
</filebox>
</filebox>


= [https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?tabs=visual-studio#queued-background-tasks Queued background tasks] =
= [https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?tabs=visual-studio#queued-background-tasks Queued background tasks] =
<filebox fn='BackgroundTaskQueue'>
<filebox fn='ItemQueue'>
public class BackgroundTaskQueue<T> : IBackgroundTaskQueue
public class ItemQueue<T> : IItemQueue
{
{
     private readonly ConcurrentQueue<T> items = new();
     private readonly ConcurrentQueue<T> queue = new();


     public void Enqueue(T item) => items.Enqueue(item);
     public void Enqueue(T item) => queue.Enqueue(item);


     public T? Dequeue()
     public bool TryDequeue(out T item) => queue.TryDequeue(out item);
    {
        var success = items.TryDequeue(out var workItem);
        return success ? workItem : default;
    }
}
}


public interface IBackgroundTaskQueue<T>
public interface IItemQueue<T>
{
{
     void Enqueue(T item);
     void Enqueue(T item);
     T? Dequeue();
     bool TryDequeue(out T item);
}
}
</filebox>
</filebox>


<filebox fn='QueuedHostedService.cs'>
<filebox fn='QueuedHostedService.cs'>
public class QueuedHostedService(IBackgroundTaskQueue taskQueue) : BackgroundService
public class QueuedHostedService(IItemQueue itemQueue) : BackgroundService
{
{
    public IItemQueue ItemQueue { get; } = itemQueue;
     protected override async Task ExecuteAsync(CancellationToken stoppingToken)
     protected override async Task ExecuteAsync(CancellationToken stoppingToken)
     {
     {
         while (!stoppingToken.IsCancellationRequested)
         while (!stoppingToken.IsCancellationRequested)
         {
         {
             var queuedTask = await TaskQueue.DequeueAsync(stoppingToken);
             await Task.Delay(1000, stoppingToken);
 
             if (ItemQueue.TryDequeueAsync(out var item))
             try
             {
             {
                 await queuedTask(stoppingToken);
                 await DoAsync(item);
             }
             }
            catch (Exception ex)
            { }
         }
         }
     }
     }
Ligne 74 : Ligne 67 :
<filebox fn='Program.cs'>
<filebox fn='Program.cs'>
services.AddHostedService<QueuedHostedService>();
services.AddHostedService<QueuedHostedService>();
services.AddSingleton<IBackgroundTaskQueue>(ctx =>
services.AddSingleton<IItemQueue<MyItem>, ItemQueue<MyItem>>();
{
    if (!int.TryParse(hostContext.Configuration["QueueCapacity"], out var queueCapacity))
        queueCapacity = 100;
    return new BackgroundTaskQueue(queueCapacity);
});
</filebox>
</filebox>


= [https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?tabs=visual-studio#timed-background-tasks Timed background tasks] =
= [https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?tabs=visual-studio#timed-background-tasks Timed background tasks] =

Dernière version du 18 septembre 2024 à 12:15

Links

Description

In ASP.NET Core, background tasks can be implemented as hosted services.

Consuming a scoped service in a background task

MyBackgroundService.cs
public class MyBackgroundService(IServiceProvider services) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var scope = services.CreateScope();
        var scopedService = scope.ServiceProvider.GetRequiredService<IMyScopedService>();
        await scopedService.DoWork(stoppingToken);
    }

    public override async Task StopAsync(CancellationToken stoppingToken)
    {
        await base.StopAsync(stoppingToken);
    }
}
Program.cs
builder.Services.AddHostedService<MyBackgroundService>();
builder.Services.AddScoped<IMyScopedService, MyScopedService>();

Queued background tasks

ItemQueue
public class ItemQueue<T> : IItemQueue
{
    private readonly ConcurrentQueue<T> queue = new();

    public void Enqueue(T item) => queue.Enqueue(item);

    public bool TryDequeue(out T item) => queue.TryDequeue(out item);
}

public interface IItemQueue<T>
{
    void Enqueue(T item);
    bool TryDequeue(out T item);
}
QueuedHostedService.cs
public class QueuedHostedService(IItemQueue itemQueue) : BackgroundService
{
    public IItemQueue ItemQueue { get; } = itemQueue;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await Task.Delay(1000, stoppingToken);
            if (ItemQueue.TryDequeueAsync(out var item))
            {
                await DoAsync(item);
            }
        }
    }
}
Program.cs
services.AddHostedService<QueuedHostedService>();
services.AddSingleton<IItemQueue<MyItem>, ItemQueue<MyItem>>();

Timed background tasks