如何从 WinForms 中的子任务更新 UI [英] How to update UI from child tasks in WinForms
问题描述
我有一个简单的小型 winforms 应用程序,它通过 TPL 任务在另一个线程上执行长时间运行的进程.在这个长期运行的过程中,我想更新 UI(进度条或其他东西).有没有办法在不需要 .ContinueWith() 的情况下做到这一点?
I've got a simple little winforms app that performs a long running process on another thread via a TPL Task. During this long running process I'd like to update the UI (the progress bar or something). Is there a way to do this without being required to .ContinueWith()?
public partial class Form1 : Form
{
private Task _childTask;
public Form1()
{
InitializeComponent();
Task.Factory.StartNew(() =>
{
// Do some work
Thread.Sleep(1000);
// Update the UI
_childTask.Start();
// Do more work
Thread.Sleep(1000);
});
_childTask = new Task((antecedent) =>
{
Thread.Sleep(2000);
textBox1.Text = "From child task";
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}
执行此代码我得到无处不在的异常:
Executing this code I get the ubiquitous exception:
跨线程操作无效:控件textBox1"是从创建它的线程以外的线程访问的.
Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.
推荐答案
是的,您可以显式调用 BeginInvoke
在要与之通信的窗口/控件上.在您的情况下,这看起来像这样:
Yes, you can explicitly call BeginInvoke
on the Window/Control that you want to communicate with. In your case this would look like this:
this.textBox.BeginInvoke(new Action(() =>
{
this.textBox.Text = "From child task.";
}));
这篇关于如何从 WinForms 中的子任务更新 UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!