Created
February 12, 2013 22:20
-
-
Save taeber/4773986 to your computer and use it in GitHub Desktop.
Asynchronous Logger using C# TPL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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