DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/BackgroundWorkerService.cs

44 lines
1.3 KiB
C#
Raw Normal View History

2021-07-21 15:29:19 +05:00
using AsbCloudApp.Services;
using Microsoft.Extensions.Hosting;
2021-09-23 17:59:31 +05:00
using System;
using System.Diagnostics;
2021-07-21 15:29:19 +05:00
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services
{
public class BackgroundWorkerService : BackgroundService
{
private readonly IBackgroundQueue tasksQueue;
public BackgroundWorkerService(IBackgroundQueue tasksQueue)
{
this.tasksQueue = tasksQueue;
}
protected override async Task ExecuteAsync(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
if (tasksQueue.TryDequeue(out var item))
await Task.Run(() => item.action(item.id), token).ConfigureAwait(false);
else
await Task.Delay(100, token).ConfigureAwait(false);
}
2021-09-23 17:59:31 +05:00
catch(Exception ex)
{
2021-09-23 17:59:31 +05:00
Trace.TraceError(ex.Message);
Console.WriteLine(ex.Message);
}
}
}
public override async Task StopAsync(CancellationToken token)
{
await base.StopAsync(token).ConfigureAwait(false);
}
}
}