Skip to content

Instantly share code, notes, and snippets.

@taeber
Created February 12, 2013 22:20
Show Gist options
  • Save taeber/4773986 to your computer and use it in GitHub Desktop.
Save taeber/4773986 to your computer and use it in GitHub Desktop.
Asynchronous Logger using C# TPL
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
public interface ILogger
{
void Log(string message);
}
class AsyncLogger : ILogger, IDisposable
{
private readonly ILogger _actual;
private readonly BlockingCollection<string> _queue;
private readonly Task _loggingTask;
public AsyncLogger(ILogger actual)
{
if (actual == null)
{
throw new ArgumentNullException("actual");
}
_actual = actual;
_queue = new BlockingCollection<string>(new ConcurrentQueue<string>());
_loggingTask = Task.Factory.StartNew(ConsumeQueueItem);
}
public void Log(string message)
{
_queue.Add(message);
}
private void ConsumeQueueItem()
{
foreach (string message in _queue.GetConsumingEnumerable())
{
_actual.Log(message);
}
}
public void Dispose()
{
_queue.CompleteAdding();
_loggingTask.Wait();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment