Windows窗体中的异步执行

我正在用C#编写Windows窗体应用程序,只需单击一下按钮即可执行许多长时间运行的过程。 这使GUI冻结直到执行。 此外,在执行期间,我将信息和状态记录到列表框中。 但是,直到执行完成,状态才会在列表框中更新。 我应该如何编码,以便状态在执行中与列表框一起更新,以便GUI不会冻结。

我是线程新手。 能否举一些如何做到这一点的例子?

在此先感谢您的帮助。

处理这些场景的最简单而有效的方法是使用BackgroundWorker

您将繁重的代码放在DoWork事件处理程序中,并通过ProgressChanged事件处理程序更新GUI。

你可以在这里找到一个教程
或者甚至更好,他们在msdn上做了“如何”
如果您在阅读后有更具体的问题,我将很乐意为您服务。

正如狒狒所说,如果你使用.Net 4或更高版本可以使用Task类,那么另一种方法是背景工作者

Task类根据需要简化了后台和UI线程上代码的执行。 使用Task类可以避免使用Task Continuation编写设置事件和回调的额外代码

Reed Copsey,Jr。在.Net上有一个关于Parallelism的非常好的系列 ,也看看它

例如,一种同步的做事方式可以

 //bad way to send emails to all people in list, that will freeze your UI foreach (String to in toList) { bool hasSent = SendMail(from, "password", to, SubjectTextBox.Text, BodyTextBox.Text); if (hasSent) { OutPutTextBox.appendText("Sent to: " + to); } else { OutPutTextBox.appendText("Failed to: " + to); } } //good way using Task class which won't freeze your UI string subject = SubjectTextBox.Text; string body = BodyTextBox.Text; var ui = TaskScheduler.FromCurrentSynchronizationContext(); List mails = new List(); foreach (string to in toList) { string target = to; var t = Task.Factory.StartNew(() => SendMail(from, "password", target, subject, body)) .ContinueWith(task => { if (task.Result) { OutPutTextBox.appendText("Sent to: " + to); } else { OutPutTextBox.appendText("Failed to: " + to); } }, ui); }