/// <summary> /// 负责发送事件 /// </summary> /// <param name="args">事件的参数</param> protected virtual void SendConsoleEvent(ConsoleEventArgs args) { // 定义一个临时的引用变量,确保多线程访问时不会发生问题 EventHandler <ConsoleEventArgs> temp = ConsoleEvent; if (temp != null) { temp(this, args); } }
/// <summary> /// 控制台输出 /// </summary> public void ConsoleOutput(string message) { EventHandlerList // 发送事件 ConsoleEventArgs args = new ConsoleEventArgs(message); SendConsoleEvent(args); // 输出消息 Console.WriteLine(message); }
/// <summary> /// 事件处理方法,注意参数固定模式 /// </summary> /// <param name="sender">事件的发送者</param> /// <param name="args">事件的参数</param> private void WriteLog(object sender, EventArgs args) { // 文件不存在的话则创建新文件 if (!File.Exists(logFile)) { using (FileStream fs = File.Create(logFile)) { } } FileInfo fi = new FileInfo(logFile); using (StreamWriter sw = fi.AppendText()) { ConsoleEventArgs cea = args as ConsoleEventArgs; sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "|" + sender.ToString() + "|" + cea.Message); } }