当控制台输出被重定向到文本框时发生跨线程操作 [英] Cross-thread operation occurs when Console output is being redirected to textbox

查看:40
本文介绍了当控制台输出被重定向到文本框时发生跨线程操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C# 和 GUI 开发的新手.如果这是一个老问题,请直接指向那个来源,我会删除这个问题.

I'm new to C# and GUI development in general. Please if this is an old question, just direct me to that source and I will take down this question.

我的情况: 所以我正在编写一个 GUI,它将一个函数的控制台输出重定向到我的 Windows 应用程序表单中的一个文本框.控制台输出仅向用户显示信息,例如设备序列号、当前软件版本等.

My Situation: So I'm writing a GUI that redirects Console output of one function to a text box in my Windows Application Form. The Console output just displays information to the user like serial number of device, current software version, etc.

我的问题:这个表格很好用,只是更新软件的过程需要几分钟,这会冻结我的表格直到它完成.现在,我知道实施后台工作者将缓解这个问题.但是,当我实现后台工作程序时,我收到以下错误.

My Problem: This form works great, except that the process of updating the software takes a couple of minutes which freezes up my form until it is complete. Now, I know that implementing a background worker will alleviate this problem. However, when I implement the background worker I receive the following error.

跨线程操作无效:控件TextBox"是从创建它的线程以外的线程访问的.

Cross-thread operation not valid: Control 'TextBox' accessed from a thread other than the thread it was created on.

我的代码总结如下:

public class Form1 : Form
{
    this.backgroundWorker1.DoWork += new
    System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
         BackgroundWorker bw = sender as BackgroundWorker;     
         BigProcess(bw);
    }

    private void BigProcess(BackgroundWorker bw)
    {
        // lengthy operation that includes lots of
        Console.WriteLine("feedback stuff for the user");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.backgroundWorker1.RunWorkerAsync();
    }
}

在这个项目中,我还有一个从 StringWriter 派生的 TextBoxStreamWriter 类,它负责控制台输出的重定向.在 TextBoxStreamWriter 中,我覆盖了 WriteLine 方法和 Write 方法.

In this project I also have a class TextBoxStreamWriter derived from StringWriter which is taking care of the redirecting of console output for me. In TextBoxStreamWriter I am overriding the WriteLine methods and the Write method.

这是我正在做的一个例子:

Here is an example of what I am doing:

public override void WriteLine(string value)
{
      base.WriteLine(DateTime.Now.ToString(value));
      textBoxOutput.AppendText(value.ToString() + Environment.NewLine);
      writer.Write(value);
}

调用此方法时抛出 InvalidOperationException.

An InvalidOperationException is thrown when this method is called.

我怎样才能使这个线程安全?任何帮助,将不胜感激.

How can I make this thread-safe? Any help would be appreciated.

推荐答案

您只需要将文本框的更新返回到 UI 线程 - 例如:

You just need to get the update to the textbox back onto the UI thread - e.g:

if (textBoxOutput.InvokeRequired)
{
  Invoke((MethodInvoker)(() => textBoxOutput.AppendText(value.ToString() + Environment.NewLine);
}
else
{
   textBoxOutput.AppendText(value.ToString() + Environment.NewLine)
}

这篇关于当控制台输出被重定向到文本框时发生跨线程操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆