2016-04-21 97 views
1

我有一个wpf应用程序,在主窗口中有一个文本框,用于在用户运行一个长过程时显示日志信息。Backgroundworker更新UI上的日志

<TextBox Grid.Row="1" Margin="10,10,10,10" AcceptsReturn="True" Name="txtLogging" TextWrapping="WrapWithOverflow" 
       Text="{Binding Path=LogText, Mode=TwoWay}" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Auto" /> 

public string LogText 
{ 
    get { return _logText; } 
    set 
    { 
     _logText = value; 
     OnPropertyChanged(); 
    } 
} 

ui上的一个按钮启动了一个过程,该过程至少需要30秒,有时甚至需要几个小时。不用说,在后台工作者上运行它是首选。问题在于程序中的日志记录类正在UI线程上创建,并且必须在工作人员执行期间被访问,以使用当前正在发生的日志更新UI。

记录器看起来像这样;

using System; 
using System.IO; 

namespace BatchInvoice 
{ 
    public enum LoggingLevel 
    { 
     Verbose = 0, 
     Info = 1, 
     Warning = 2, 
     Error = 3 
    } 
    public sealed class Logger 
    { 

     string _logFile; 
     static Logger() { } 
     public bool LogToDataBase = false; 
     public bool LogToFile = true; 
     public bool LogToScreen = false; 
     private Logger() 
     { 
      //string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); 
      string filePath = Directory.GetCurrentDirectory(); 
      filePath = filePath + @"\LogFiles"; 
      string extension = ".log"; 
      if (!Directory.Exists(filePath)) 
      { 
       Directory.CreateDirectory(filePath); 
      } 
      /*string currentDir = Environment.CurrentDirectory; 
      DirectoryInfo directory = new DirectoryInfo(currentDir); 
      string fullDirectory = directory.FullName;*/ 
      string date = (DateTime.Now).ToString("yyyyMMddHHmmss"); 
      _logFile = filePath + "\\" + date + extension; 
      minimumLoggingLevel = LoggingLevel.Info; 
     } 
     private LoggingLevel minimumLoggingLevel; 
     public static void SetMinimumLoggingLevel(LoggingLevel minimum) 
     { 
      Instance.minimumLoggingLevel = minimum; 
     } 
     public static LoggingLevel GetMinimumLoggingLevel() 
     { 
      return Instance.minimumLoggingLevel; 
     } 
     private static readonly Logger instance = new Logger(); 
     public static Logger Instance 
     { 
      get 
      { 
       return instance; 
      } 
     } 
     public static void Write(string content) 
     { 
      using (StreamWriter fileWriter = File.AppendText(Instance._logFile)) 
      { 
       fileWriter.WriteLine(content); 
      } 
     } 
     public static void Write(string content, LoggingLevel warningLevel) 
     { 
      if (Instance.minimumLoggingLevel <= warningLevel) 
      { 
       if (Instance.LogToFile) 
       { 
        using (StreamWriter fileWriter = File.AppendText(Instance._logFile)) 
        { 
         fileWriter.WriteLine(warningLevel.ToString() + ": " + content); 
        } 
       } 
       if (Instance.LogToScreen) 
        ScreenLogging.Write(content, warningLevel); 
       if (Instance.LogToDataBase) 
       { 
        //enter database loggign code here. 
       } 
      } 
     } 
    } 
} 

using System.Windows; 
using System.Windows.Controls; 

namespace BatchInvoice 
{ 
    public class ScreenLogging 
    { 
     private static ScreenLogging _instance; 
     private ScreenLogging() { } 
     public static ScreenLogging Instance 
     { 
      get 
      { 
       if(_instance == null) 
       { 
        _instance = new ScreenLogging(); 
       } 
       return _instance; 
      } 
     } 
     private TextBox _target; 
     public static void SetTarget(TextBox target) 
     { 
      Instance._target = target; 
     } 
     public static void Write(string content, LoggingLevel warningLevel) 
     { 
      //MessageBox.Show(content, warningLevel.ToString()); 
      Instance._target.AppendText(warningLevel.ToString() + ": " + content + "\n"); 
     } 
    } 
} 

(是的,有是screenlogging被分成不同的类的理由,但我真的希望我没有更改)我能做些什么,使这个日志类来电反思来自后台工作者的UI?我是否应该将LogText属性更改为从外部文件或这些行中读取?目前我没有实现后台工作,所以日志只显示任务完成后,但我需要能够监视其运行进度。当我尝试将它放入后台工作器时,它遇到了试图访问记录器的代码行时出现错误。

+0

你可以使用Bgworker或任务和更新您的文本框中有只 – Firoz

回答

1

由于您的问题似乎不是重写所有日志电话,我会后做,仅仅通过改变ScreenLogging.Write方法的另一种方式。我希望这对你有用,因为你不需要改变你的调用Logger.Write方法。

public class ScreenLogging 
{ 
    private static ScreenLogging _instance; 
    private ScreenLogging() { } 
    public static ScreenLogging Instance 
    { 
     get 
     { 
      if (_instance == null) 
      { 
       _instance = new ScreenLogging(); 
      } 
      return _instance; 
     } 
    } 
    private TextBox _target; 
    public static void SetTarget(TextBox target) 
    { 
     Instance._target = target; 
    } 
    public static void Write(string content, LoggingLevel warningLevel) 
    { 
     var appendTextAction = new Action(() => 
     { 
      var text = warningLevel.ToString() + ": " + content + "\n"; 
      Instance._target.AppendText(text); 
     }); 

     // Only the thread that the Dispatcher was created on may access the 
     // DispatcherObject directly. To access a DispatcherObject from a 
     // thread other than the thread the DispatcherObject was created on, 
     // call Invoke and BeginInvoke on the Dispatcher the DispatcherObject 
     // is associated with. 
     // You can set the priority to Background, so you guarantee that your 
     // key operations will be processed first, and the screen updating 
     // operations will happen only after those operations are done. 
     Instance._target.Dispatcher.Invoke(appendTextAction, 
      DispatcherPriority.Background); 
    } 
} 
+0

大约一小时前刚刚更改为此。我为记录器和屏幕记录类的实例添加了一个锁,它似乎工作正常。谢谢! – dragoncmd

+0

快乐你找到解决方案!对不起,延误了,我很忙,只是再次看到你的问题。 – Ismael

2

由于您试图从另一个线程更新UI,因此必须以特殊方式执行此操作,其中线程必须同步以在它们之间传输数据。换句话说,就像BackgroundWorker需要暂停来更新UI。它可以使用BackgroundWorker的ProgressChanged事件和ReportProgress方法完成。下面是一个简单的例子:

private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     // I guess this is how you are using your logger, right? 
     ScreenLogging.SetTarget(this.txtLogging); 

     BackgroundWorker worker = new BackgroundWorker(); 

     // Your classic event to do the background work... 
     worker.DoWork += Worker_DoWork; 

     // Here you can sender messages to UI. 
     worker.ProgressChanged += Worker_ProgressChanged; 

     // Don't forget to turn this property to true. 
     worker.WorkerReportsProgress = true; 

     worker.RunWorkerAsync(); 
    } 

    private void Worker_DoWork(object sender, DoWorkEventArgs e) 
    { 
     var worker = sender as BackgroundWorker; 

     Thread.Sleep(3000); 

     // ReportProgress sends two values to the ProgressChanged method, for the 
     // ProgressChangedEventArgs object. The first one is the percentage of the 
     // work, and the second one can be any object that you need to pass to UI. 
     // In a simple example, I am passing my log message and just putting 
     // any random value at progress, since it does not matter here. 
     worker.ReportProgress(0, "Test!"); 
    } 

    private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e) 
    { 
     // Here you get your UserState object, wich is my string message passed on 
     // with the ReportProgress method above. 
     var message = e.UserState as string; 

     // Then you call your log as always. Simple, right? 
     ScreenLogging.Write(message, LoggingLevel.Info); 
    } 
+0

这是有道理的,但要求所有来电改写到当前存在的记录。这些文件也被用于相关的命令行应用程序中。是否有可能检测到一段代码是从主线程运行还是不是?如果我可以使用可以检查其是否从后台线程运行的东西来覆盖Logger.Write()方法,并且如果是,则调用报告进度方法,那会更好。 – dragoncmd