Initial Commit ...
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using xLoggingService.Models;
|
||||
using xLoggingService.Interfaces;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace xLoggingService.Background
|
||||
{
|
||||
public sealed class XLogDispatcher : IDisposable
|
||||
{
|
||||
private readonly Task worker;
|
||||
private readonly BlockingCollection<XLogEntry> queue;
|
||||
private readonly IReadOnlyCollection<IXLogWriter> writers;
|
||||
private readonly CancellationTokenSource cancellation = new CancellationTokenSource();
|
||||
|
||||
public XLogDispatcher(
|
||||
int capacity,
|
||||
IEnumerable<IXLogWriter> writers
|
||||
)
|
||||
{
|
||||
//
|
||||
queue = new BlockingCollection<XLogEntry>(Math.Max(100, capacity));
|
||||
this.writers = new List<IXLogWriter>(writers)
|
||||
.AsReadOnly();
|
||||
|
||||
//
|
||||
worker = Task.Run(RunAsync);
|
||||
}
|
||||
|
||||
public void Enqueue(XLogEntry entry)
|
||||
{
|
||||
if (!queue.IsAddingCompleted && !queue.TryAdd(entry)) { }
|
||||
}
|
||||
|
||||
private async Task RunAsync()
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
foreach (var entry in queue.GetConsumingEnumerable(cancellation.Token))
|
||||
{
|
||||
//
|
||||
foreach (var writer in writers)
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
await writer.WriteAsync(entry, cancellation.Token)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
//
|
||||
queue.CompleteAdding();
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
worker.Wait(TimeSpan.FromSeconds(10));
|
||||
}
|
||||
catch { }
|
||||
|
||||
//
|
||||
cancellation.Cancel();
|
||||
queue.Dispose();
|
||||
cancellation.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user