我在项目中中引入了System.Windows.Forms,然后用单例模式实现的一个listbox日志记录功能
不过在多线程访问的时候有时候还是会出问题。
大侠帮忙看一下,下面代码。

解决方案 »

  1.   

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms;
    using System.Drawing;namespace Common
    {
        /// <summary>
        /// 日志工具
        /// </summary>
        public class LogUtil
        {
            public static LogUtil Instance = new LogUtil();        private LogUtil() { }        public void PrintErrorMessage(string message)
            {
                this.RunThread(message);
            }        public void PrintLog(string message)
            {
                this.RunThread(message);
            }        private void RunThread(string message)
            {
                WaitCallback wc = new WaitCallback(SetLogValue);
                ThreadPool.QueueUserWorkItem(wc, FormatUtil.GetCurrentTime() + "  " + message);
            }        private void SetLogValue(object message)
            {
                Form form = Form.ActiveForm;
                form.Invoke(new Action(delegate()
                {
                    ListBox listBox = form.Controls["ltbLog"] as ListBox;
                    // 记录一千行日志
                    if (listBox.Items.Count > 1000)
                    {
                        listBox.Items.Clear();
                    }
                    listBox.Items.Add(message.ToString());
                    listBox.SelectedIndex = listBox.Items.Count - 1;
                    listBox.ClearSelected();
                }));
            }
        }
    }
      

  2.   

    form.Invoke(new Action(delegate()这一行报未处理NullReferenceException。
      

  3.   

    Form form = Form.ActiveForm;
    调试看看form是否等于null
    没有再去掉new Action(看看
    form.Invoke(delegate()
      {
      

  4.   

    是啊,所以说现在的问题演变成了如何在后台获取Form窗体,我猜想可能是Form窗体失去焦点所以到了Form.ActiveForm获取不到了。
      

  5.   

    解决了
    Form form = Form.ActiveForm;改成Form form = Application.OpenForms[0];
    完美解决~~~