我的程序中有一个简单的文本框。 其他功能:来自用户textbox1的另一个输入和一个按钮。 一旦用户在textbox1中输入一个值,然后按下该按钮,我就开始检查并向用户打印消息。我的问题是我没有实时看到这些消息,一次一个。最后会立即显示这些消息。 我没有定义数据绑定,因为我认为,因为它是一件简单的事情,我不需要它,或者我错了? 这是我程序的一小部分,它位于按钮单击事件处理程序中。
MainText.AppendText("Starting Refiling...\u2028");
foreach (DocumentData doc in Docs)
{
try
{
wsProxy.RefileDocument(doc);
MainText.AppendText(String.Format("Refilling doc # {0}.{1}\u2028", doc.DocNum, doc.DocVer));
}
catch (Exception exc)
{
if (exc.Message.Contains("Document is in use") == true)
MainText.AppendText(String.Format("There was a problem refilling doc # {0}, it is in use.\u2028",doc.DocNum));
else
MainText.AppendText(String.Format("There was a problem refilling doc # {0} : {1}.\u2028", doc.DocNum, exc.Message));
}
}
答案 0 :(得分:1)
您正在GUI线程中进行所有循环/打印。基本上你给它新的项目展示,而不是给它时间来展示它们。创建一个background worker并让他在你发布的foreach循环中完成工作。这应该允许UI线程在文本更改时更新视图,而不是在最后一次更新所有更改。我发布的链接包含了如何使用backgroundworker类的示例,但这就是我要做的。
创建后台工作者:
private readonly BackgroundWorker worker = new BackgroundWorker();
初始化他:
public MainWindow()
{
InitializeComponent();
worker.DoWork += worker_DoWork;
}
为他创建一个任务:
void worker_DoWork( object sender, DoWorkEventArgs e)
{
// Set up a string to hold our data so we only need to use the dispatcher in one place
string toAppend = "";
foreach (DocumentData doc in Docs)
{
toAppend = "";
try
{
wsProxy.RefileDocument(doc);
toAppend = String.Format("Refilling doc # {0}.{1}\u2028", doc.DocNum, doc.DocVer);
}
catch (Exception exc)
{
if (exc.Message.Contains("Document is in use"))
toAppend = String.Format("There was a problem refilling doc # {0}, it is in use.\u2028",doc.DocNum);
else
toAppend = String.Format("There was a problem refilling doc # {0} : {1}.\u2028", doc.DocNum, exc.Message);
}
// Update the text from the main thread to avoid exceptions
Dispatcher.Invoke((Action)delegate
{
MainText.AppendText(toAppend);
});
}
}
当您按下按钮事件时启动他:
private void Button_Click(object sender, RoutedEventArgs e)
{
worker.RunWorkerAsync();
}