用于I \ O操作的单独线程听起来很合理。
例如,记录用户在同一UI线程中按下了哪些按钮不是很好。这样的UI会随机挂起,并且性能会变慢。
解决方案是将事件与其处理分离。
这是来自游戏开发世界的有关生产者-消费者问题和事件队列的大量信息。
通常会有类似的代码
///Never do this!!!
public void WriteLog_Like_Bastard(string msg)
{
lock (_lockBecauseILoveThreadContention)
{
File.WriteAllText("c:\\superApp.log", msg);
}
}
这种方法将导致线程争用。所有处理线程都将努力争取能够立即获得锁定并写入同一文件。
有些人可能会尝试解除锁定。
public void Log_Like_Dumbass(string msg)
{
try
{ File.Append("c:\\superApp.log", msg); }
catch (Exception ex)
{
MessageBox.Show("Log file may be locked by other process...")
}
}
}
如果2个线程同时进入方法,则无法预测结果。
因此最终开发人员将完全禁用日志记录...
有可能解决吗?
是。
可以说我们有接口:
public interface ILogger
{
void Debug(string message);
// ... etc
void Fatal(string message);
}
而不是等待锁和执行每当时间阻止文件操作ILogger
被称为我们将新添加的LogMessage到Penging消息队列和返回到更重要的事情:
public class AsyncLogger : ILogger
{
private readonly BlockingCollection<LogMessage> _pendingMessages;
private readonly Type _loggerFor;
private readonly IThreadAdapter _threadAdapter;
public AsyncLogger(BlockingCollection<LogMessage> pendingMessages, Type loggerFor, IThreadAdapter threadAdapter)
{
_pendingMessages = pendingMessages;
_loggerFor = loggerFor;
_threadAdapter = threadAdapter;
}
public void Debug(string message)
{
Push(LoggingLevel.Debug, message);
}
public void Fatal(string message)
{
Push(LoggingLevel.Fatal, message);
}
private void Push(LoggingLevel importance, string message)
{
// since we do not know when our log entry will be written to disk, remember current time
var timestamp = DateTime.Now;
var threadId = _threadAdapter.GetCurrentThreadId();
// adds message to the queue in lock-free manner and immediately returns control to caller
_pendingMessages.Add(LogMessage.Create(timestamp, importance, message, _loggerFor, threadId));
}
}
我们已经完成了这个简单的 异步记录器。
下一步是处理传入消息。
为简单起见,让我们启动新线程并永远等待,直到应用程序退出,或者异步记录器将新消息添加到待处理队列中。
public class LoggingQueueDispatcher : IQueueDispatcher
{
private readonly BlockingCollection<LogMessage> _pendingMessages;
private readonly IEnumerable<ILogListener> _listeners;
private readonly IThreadAdapter _threadAdapter;
private readonly ILogger _logger;
private Thread _dispatcherThread;
public LoggingQueueDispatcher(BlockingCollection<LogMessage> pendingMessages, IEnumerable<ILogListener> listeners, IThreadAdapter threadAdapter, ILogger logger)
{
_pendingMessages = pendingMessages;
_listeners = listeners;
_threadAdapter = threadAdapter;
_logger = logger;
}
public void Start()
{
// Here I use 'new' operator, only to simplify example. Should be using interface '_threadAdapter.CreateBackgroundThread' to allow unit testing
Thread thread = new Thread(MessageLoop);
thread.Name = "LoggingQueueDispatcher Thread";
thread.IsBackground = true;
thread.Start();
_logger.Debug("Asked to start log message Dispatcher ");
_dispatcherThread = thread;
}
public bool WaitForCompletion(TimeSpan timeout)
{
return _dispatcherThread.Join(timeout);
}
private void MessageLoop()
{
_logger.Debug("Entering dispatcher message loop...");
var cancellationToken = new CancellationTokenSource();
LogMessage message;
while (_pendingMessages.TryTake(out message, Timeout.Infinite, cancellationToken.Token))
{
// !!!!! Now it is safe to use File.AppendAllText("c:\\my.log") without ever using lock or forcing important threads to wait.
// this is example, do not use in production
foreach (var listener in _listeners)
{
listener.Log(message);
}
}
}
}
我正在传递自定义侦听器链。您可能只想发送呼叫记录框架(log4net
等)。
这是其余的代码:
public enum LoggingLevel
{
Debug,
// ... etc
Fatal,
}
public class LogMessage
{
public DateTime Timestamp { get; private set; }
public LoggingLevel Importance { get; private set; }
public string Message { get; private set; }
public Type Source { get; private set; }
public int ThreadId { get; private set; }
private LogMessage(DateTime timestamp, LoggingLevel importance, string message, Type source, int threadId)
{
Timestamp = timestamp;
Message = message;
Source = source;
ThreadId = threadId;
Importance = importance;
}
public static LogMessage Create(DateTime timestamp, LoggingLevel importance, string message, Type source, int threadId)
{
return new LogMessage(timestamp, importance, message, source, threadId);
}
public override string ToString()
{
return string.Format("{0} [TID:{4}] {1:h:mm:ss} ({2})\t{3}", Importance, Timestamp, Source, Message, ThreadId);
}
}
public class LoggerFactory : ILoggerFactory
{
private readonly BlockingCollection<LogMessage> _pendingMessages;
private readonly IThreadAdapter _threadAdapter;
private readonly ConcurrentDictionary<Type, ILogger> _loggersCache = new ConcurrentDictionary<Type, ILogger>();
public LoggerFactory(BlockingCollection<LogMessage> pendingMessages, IThreadAdapter threadAdapter)
{
_pendingMessages = pendingMessages;
_threadAdapter = threadAdapter;
}
public ILogger For(Type loggerFor)
{
return _loggersCache.GetOrAdd(loggerFor, new AsyncLogger(_pendingMessages, loggerFor, _threadAdapter));
}
}
public class ThreadAdapter : IThreadAdapter
{
public int GetCurrentThreadId()
{
return Thread.CurrentThread.ManagedThreadId;
}
}
public class ConsoleLogListener : ILogListener
{
public void Log(LogMessage message)
{
Console.WriteLine(message.ToString());
Debug.WriteLine(message.ToString());
}
}
public class SimpleTextFileLogger : ILogListener
{
private readonly IFileSystem _fileSystem;
private readonly string _userRoamingPath;
private readonly string _logFileName;
private FileStream _fileStream;
public SimpleTextFileLogger(IFileSystem fileSystem, string userRoamingPath, string logFileName)
{
_fileSystem = fileSystem;
_userRoamingPath = userRoamingPath;
_logFileName = logFileName;
}
public void Start()
{
_fileStream = new FileStream(_fileSystem.Path.Combine(_userRoamingPath, _logFileName), FileMode.Append);
}
public void Stop()
{
if (_fileStream != null)
{
_fileStream.Dispose();
}
}
public void Log(LogMessage message)
{
var bytes = Encoding.UTF8.GetBytes(message.ToString() + Environment.NewLine);
_fileStream.Write(bytes, 0, bytes.Length);
}
}
public interface ILoggerFactory
{
ILogger For(Type loggerFor);
}
public interface ILogListener
{
void Log(LogMessage message);
}
public interface IThreadAdapter
{
int GetCurrentThreadId();
}
public interface IQueueDispatcher
{
void Start();
}
入口点:
public static class Program
{
public static void Main()
{
Debug.WriteLine("[Program] Entering Main ...");
var pendingLogQueue = new BlockingCollection<LogMessage>();
var threadAdapter = new ThreadAdapter();
var loggerFactory = new LoggerFactory(pendingLogQueue, threadAdapter);
var fileSystem = new FileSystem();
var userRoamingPath = GetUserDataDirectory(fileSystem);
var simpleTextFileLogger = new SimpleTextFileLogger(fileSystem, userRoamingPath, "log.txt");
simpleTextFileLogger.Start();
ILogListener consoleListener = new ConsoleLogListener();
ILogListener[] listeners = new [] { simpleTextFileLogger , consoleListener};
var loggingQueueDispatcher = new LoggingQueueDispatcher(pendingLogQueue, listeners, threadAdapter, loggerFactory.For(typeof(LoggingQueueDispatcher)));
loggingQueueDispatcher.Start();
var logger = loggerFactory.For(typeof(Console));
string line;
while ((line = Console.ReadLine()) != "exit")
{
logger.Debug("you have entered: " + line);
}
logger.Fatal("Exiting...");
Debug.WriteLine("[Program] pending LogQueue will be stopped now...");
pendingLogQueue.CompleteAdding();
var logQueueCompleted = loggingQueueDispatcher.WaitForCompletion(TimeSpan.FromSeconds(5));
simpleTextFileLogger.Stop();
Debug.WriteLine("[Program] Exiting... logQueueCompleted: " + logQueueCompleted);
}
private static string GetUserDataDirectory(FileSystem fileSystem)
{
var roamingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var userDataDirectory = fileSystem.Path.Combine(roamingDirectory, "Async Logging Sample");
if (!fileSystem.Directory.Exists(userDataDirectory))
fileSystem.Directory.CreateDirectory(userDataDirectory);
return userDataDirectory;
}
}