gpt4 book ai didi

.net - 如何从 TPL 任务更新 WPF 控件?

转载 作者:行者123 更新时间:2023-12-04 14:42:32 24 4
gpt4 key购买 nike

如何从 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 ?
}
}
}

谢谢!

最佳答案

您需要将执行您的工作的委托(delegate)传递给 BeginInvoke
BeginInvoke 将在 UI 线程上异步运行此委托(delegate)。

例如:

Dispatcher.BeginInvoke(new Action(delegate {
textBox2.Text = number.ToString();
}));

关于.net - 如何从 TPL 任务更新 WPF 控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7726697/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com