C#:从多个线程更新文本框中的控制台

时间:2016-09-13 15:00:15

标签: c# multithreading winforms

在我的应用程序中,我试图将控制台的输出显示到win窗体文本框中。只要我在gui线程中,这是有效的。但是当我从另一个线程写入控制台时,我得到一个InvalidOperationException。这是我使用的代码:

形式:

public partial class Form1 : Form
    {
        Crawler crawler = new Crawler();
        Log log = null;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            log = new Log(tbLogOutput);    
            Console.SetOut(log);
        }
    }
}

在Textwriter中:

class Log : TextWriter
    {
        TextBox _output = null;

        public Log(TextBox output)
        {
            _output = output;
        }

        public override void Write(char value)
        {
            base.Write(value);
            _output.AppendText(value.ToString()); // When character data is written, append it to the text box.
        }

        public override Encoding Encoding
        {
            get { return System.Text.Encoding.UTF8; }
        }
    }

1 个答案:

答案 0 :(得分:0)

可能值得在Google“从线程c#更新用户界面”中输入

How to update the GUI from another thread in C#?