更新UI的WinForms从后台线程结果 [英] Update Winforms UI from background thread result
问题描述
这可能是一个愚蠢的问题,但我无法找到计算器一个答案。
This is probably a silly question, but I could not find an answer on stackoverflow.
我有运行一个线程在WinForm的应用程序一键点击事件caclulate结果的形式来显示。
I have a button click event in a Winform app that runs a thread to caclulate a result to display in a form.
如何更新当线程计算的结果,表单的用户界面?
How do I update the Forms UI when the thread has calculated the result?
private void btnRequestR2Approval_Click(object sender, EventArgs e)
{
if (User.IsLogged)
{
ValidationResults results = new ValidationResults();
results.Show();
Logger log = Logger.Instance();
Logger.NewLogAddedHandler messageDelegate = new Logger.NewLogAddedHandler(results.NewLogMessage);
if (!log.IsEventHandlerRegistered())
{
log.NewLogAdded += messageDelegate;
}
ThreadStart operation = new ThreadStart(ValidateAndSubmit);
Thread theThread = new Thread(operation);
theThread.Start();
}
else
{
MessageBox.Show("Please login");
}
}
感谢您
推荐答案
最简单的方法,用于执行的WinForms后台任务是使用<一个href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx?ppud=4">BackgroundWorker.
The simplest technique for executing a background task in WinForms is to use a BackgroundWorker.
- 拖放到一个表单。
- 线了的事件。作为最低要求,使用
的DoWork
。你可能还需要RunWorkerCompleted
。 - 写您的后台任务在
的DoWork
事件。 - 写在
RunWorkerCompleted
事件的任何用户界面的变化。 - 呼叫
backgroundWorker1.RunWorkerAsync();
揭开序幕的过程中,可能是由一些按钮处理程序 。
- Drop it onto a form.
- Wire up the events. As a minimum, use
DoWork
. You'll probably also wantRunWorkerCompleted
. - Write your background task in the
DoWork
event. - Write any UI changes in the
RunWorkerCompleted
event. - Call
backgroundWorker1.RunWorkerAsync();
to kick off the process, probably from some button handler.
使用一个BackgroundWorker避免了所有烦人的线程处理和IsInvokeRequired的东西。
Using a BackgroundWorker avoids all the annoying thread handling and IsInvokeRequired stuff.
下面是一个更详细的如何对文章。
这篇关于更新UI的WinForms从后台线程结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!