Dev*_*per 2 .net parallel-processing wpf dispatcher task-parallel-library
如何从TPL任务更新WPF控件?
好吧所以我尝试了一些方案来使用Dispatcher,但无论如何它都会给出错误.我需要帮助的人!
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//Application.Current.Dispatcher.Invoke((Action)MyInit);
backgroundDBTask = Task.Factory.StartNew(() =>
{
DoSomething1();
}, TaskCreationOptions.LongRunning);
backgroundDBTask.ContinueWith((t) =>
{
// ... UI update work here ...
},
TaskScheduler.FromCurrentSynchronizationContext());
}
void DoSomething1()
{
// MyInit();
int number = 0;
while (true)
{
if (state)
{
Thread.Sleep(1000);
Console.WriteLine("Begin second task... {0}", number++);
// mostCommonWords = GetMostCommonWords(words) + string.Format(" Begin second task... {0}", number++);
textBox2.Text = (number++).ToString(); // Gives the error
Dispatcher.BeginInvoke(); // How it should be ?
}
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
您需要传递一份代理人来完成您的工作BeginInvoke.
BeginInvoke将在UI线程上异步运行此委托.
例如:
Dispatcher.BeginInvoke(new Action(delegate {
textBox2.Text = number.ToString();
}));
Run Code Online (Sandbox Code Playgroud)