C# 使用BackGroundWorker调用控件
有奇怪的问题,无法解决 正在尝试将RichTextBox转换为我的应用程序中的日志“控制台”。当然,我在应用程序中使用线程,当然我知道调用 让我们看看我的代码C# 使用BackGroundWorker调用控件,c#,multithreading,winforms,singleton,invoke,C#,Multithreading,Winforms,Singleton,Invoke,有奇怪的问题,无法解决 正在尝试将RichTextBox转换为我的应用程序中的日志“控制台”。当然,我在应用程序中使用线程,当然我知道调用 让我们看看我的代码 MainForm启动一个BackGroundWorker来完成这项工作。我的BackGroundWorker启动许多线程,在事件发生时调用DebugConsole。对于这个问题,我举一个简单的例子 bkw.DoWork += (obj, a) => DebugConsole.DoSomeWork(msg, Color.Coral);
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
还实现了调用下一个think的单例模式
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();
}
}
}
问题:我无法控制任何事情
- 我做错了什么李>
- 谁能告诉我我错过了什么
this.Invoke((MethodInvoker)delegate
{
Instance.LogTextEvent(ev,clr);
});
您是否使用Visual Studio调试器来找出实际执行的代码?当然,我使用VS来调试它。。。所有的代码似乎都能正常工作:您的代码未能完成您想要的任务,当您调试它时,它似乎正在完成您想要的任务,这一定是因为您未能正确调试问题(即错误使用调试器,从而无法识别错误)。当然,如果没有完整的代码示例,任何其他人都不能代表您进行任何调试。我在您发布的代码中看到的最大问题是用于调用的复制/粘贴。但在这种情况下,没有任何迹象表明存在实际问题。您需要改进或改进调试。:)您可能正在使用过多的BeginInvoke()调用来启动UI线程。你会看到它燃烧100%的核心,试图跟上,但没有成功。它停止处理优先级较低的任务,比如绘画。除了降低BeginInvoke呼叫速率之外,限制RTB中的文本量也非常重要。那些AppendText()调用在一段时间后会变得非常昂贵。
LogTextEvent
的实现会封送到UI线程以实现它。