使用多线程应用程序记录WPF文本框 [英] WPF textbox logging with multithread application

查看:209
本文介绍了使用多线程应用程序记录WPF文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#和WPF的新手,请原谅我这个问题是否太基础了。


我创建了一个带有文本框的WPF应用程序,其中多个线程正在写日志调用Log方法时的文本。


代码似乎工作但每次我在代码(VS)中放入av断点时都会以错误结束。为什么?

 private void Log(string text)
{
if(string.IsNullOrEmpty(text))
返回;

{

}
if(textBoxLog.Dispatcher.Thread == Thread.CurrentThread)
{
textBoxLog.Text + = text + Environment.NewLine;
textBoxLog.ScrollToEnd();
}
else
{
this.Dispatcher.Invoke(()=> textBoxLog.Text + = text + Environment.NewLine);
this.Dispatcher.Invoke(()=> textBoxLog.ScrollToEnd());
}
}



解决方案

嗨Bjorn,


我用多个线程来调用你的方法,但我不知道在我身边得到任何错误,你有错误吗?这是我的代码,你可以看看:

 for(Int32 i = 0; i< 10; i ++)
{
// var t = Task.Run(()=> Log(" test" + i));
线程t =新线程(()=> Log("test"));
t.Start();
}

最好的问候,


Cherry



I'm new to C# and WPF so excuse me if this question is too basic.

I have created a WPF application with a textbox where multiple threads are writing log text when calling the Log methode.

The code seems to work but ends with an error everytime i put av break point in the code (VS). Why?

        private void Log(string text)
        {
            if (string.IsNullOrEmpty(text))
                return;

            {

            }
            if (textBoxLog.Dispatcher.Thread == Thread.CurrentThread)
            {
                textBoxLog.Text += text + Environment.NewLine;
                textBoxLog.ScrollToEnd();
            }
            else
            {
                this.Dispatcher.Invoke(() => textBoxLog.Text += text +Environment.NewLine);
                this.Dispatcher.Invoke(() => textBoxLog.ScrollToEnd());
            }
        }


解决方案

Hi Bjorn,

I use multiple thread to call your method, but I don't get any error at my side, where you have error? Here is the my code, you can take a look:

            for(Int32 i=0;i<10;i++)
            {
                //var t = Task.Run(() => Log("test" + i));
                Thread t = new Thread(()=>Log("test"));
                t.Start();
            }

Best Regards,

Cherry


这篇关于使用多线程应用程序记录WPF文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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