使用BackGroundWorker调用Control

时间:2015-01-04 03:19:38

标签: c# multithreading winforms singleton invoke

有奇怪的问题,无法解决问题。

尝试将RichTextBox转换为日志控制台'在我的申请中。当然我在我的应用程序中使用线程,当然我知道Invoke。

让我们来看看我的代码。

MainForm启动BackGroundWorker来完成工作。我的BackGroundWorker启动了许多在事件中调用DebugConsole的线程。对于这个问题,我举了一个简单的例子。

bkw.DoWork += (obj, a) => DebugConsole.DoSomeWork(msg, Color.Coral);
bkw.RunWorkerAsync(); 

DebugConsole是一个实现单例模式以获取DoSomeWork函数的类。

让我们看一下DebugConsole课程:

class DebugConsole
{
        private static readonly DebugConsole instance = new DebugConsole();

        public static DebugConsole Instance
        {
            get { return instance; }
        }

        public static void DoSomeWork(string msg, Color color)
        {
            Instance.DebugBox(msg, color);
        }

        private void DebugBox(string msg, Color color)
        {
            MainForm.DoSomeWork(msg, color);
        }
    }

同样,你看到我的MainForm也实现了单一模式,可以调用下一个想法。

private static readonly MainForm instance = new MainForm();

public static MainForm Instance
{
    get { return instance; }
}

public static void DoSomeWork(string ev, Color clr)
{
    Instance.LogTextEvent(ev,clr);
}

LogTextEvent在我的应用程序中做最后一次思考,它在我的RichTextBox中写了一条消息,这就是问题所在。它不会写/调用我的控件。

public void LogTextEvent(string eventText, Color textColor)
{
        var nDateTime = DateTime.Now.ToString("hh:mm:ss tt") + " - ";
        if (rtbDebug.InvokeRequired)
        {
            rtbDebug.BeginInvoke((MethodInvoker) delegate
            {
                rtbDebug.SelectionStart = rtbDebug.Text.Length;
                rtbDebug.SelectionColor = textColor;

                if (rtbDebug.Lines.Length == 0)
                {
                    rtbDebug.AppendText(nDateTime + eventText);
                    rtbDebug.ScrollToCaret();
                    rtbDebug.AppendText(Environment.NewLine);
                }
                else
                {
                    rtbDebug.AppendText(nDateTime 
                                      + eventText 
                                      + Environment.NewLine);
                    rtbDebug.ScrollToCaret();
                }
            });
        }
        else
        {
            rtbDebug.SelectionStart = rtbDebug.Text.Length;
            rtbDebug.SelectionColor = textColor;

            if (rtbDebug.Lines.Length == 0)
            {
                rtbDebug.AppendText(nDateTime + eventText);
                rtbDebug.ScrollToCaret();
                rtbDebug.AppendText(Environment.NewLine);
            }
            else
            {
                rtbDebug.AppendText(nDateTime 
                                  + eventText 
                                  + Environment.NewLine);
                rtbDebug.ScrollToCaret();
            }
        }
    }

问题:我的控制中没有任何反应。

  • 我做错了什么?
  • 有人可以告诉我我错过了什么吗?

1 个答案:

答案 0 :(得分:-1)

试试这个

this.Invoke((MethodInvoker)delegate
        {
             Instance.LogTextEvent(ev,clr);
        });