public string Take() { ILogMessage message = null; while (message == null) { BlockingCollection <ILogMessage> localMessageQueueReference = null; lock (syncObj) { //Only make a new one if cancel is requested if (currentTakeCancelToken == null || currentTakeCancelToken.IsCancellationRequested) { currentTakeCancelToken = new CancellationTokenSource(); //create a new cancelation token for taking. } localMessageQueueReference = messageCollection; } //TODO: Rewrite this hack try { message = messageCollection.Take(currentTakeCancelToken.Token); //This could loop forever but if we can't take any non-null items there is a design issue. } catch (ObjectDisposedException e) { //This is bad practice to control flow by exceptions. However, if this does occur it means Clear was called while this was blocking and the cancelation didn't happen //quick enough. We just need to continue and things should be fine. continue; } catch (OperationCanceledException e) { //This means that during take it was canceled. We should just continue after this occurs. continue; } } //TODO: This is not working. Fix it so we can provide a StringBuilder to the message. if (stringBuilderService.isAvailable) { try { using (var sb = stringBuilderService.Get()) { //return message.BuildMessage(new StringBuilder()); return(message.BuildMessage(sb.Get())); } } catch (Exception e) { return("Error: StringBuilder service unavailable or unable to build a " + typeof(ILogMessage).ToString() + " for other reasons. Exception: " + e.GetType().ToString() + " Message: " + e.Message + " StackTrace: " + e.StackTrace); } } else { throw new Exception("Error: Message preparing cannot aquire a StringBuilder service."); } }