【发布时间】:2020-03-02 11:16:00
【问题描述】:
这是我的代码,主要的 xaml.cs 文件:
//using statements...
namespace WpfAppTestRichTextBox
{
public partial class MainWindow : Window
{
public Paragraph p = new Paragraph();
public MainWindow()
{
InitializeComponent();
Start();
}
// Initialize the richTextBox...
public void Start()
{
Run r = new Run("");
p.Inlines.Add(r);
richTextBox.Document.Blocks.Add(p);
}
// Button Click and Start a new Thread to record time for each second.
private void Button_Click(object sender, RoutedEventArgs e)
{
System.Threading.Thread th = new System.Threading.Thread(ChangeText);
th.Start();
}
public void ChangeText()
{
while(true)
{
this.Dispatcher.Invoke(new Action(() =>
{
string time = System.DateTime.Now.ToString() + "\n";
Run r = new Run(time);
p.Inlines.Add(r);
System.Threading.Thread.Sleep(1000);
}));
}
}
}
}
我将新的 Run() 添加到 Paragraph 并期望richTextBox 的内容将被刷新。但它在 while() 中阻塞并且在richTextBox 中什么也不打印。
我该如何解决这个问题?
【问题讨论】:
标签: c# wpf windows multithreading user-interface