gpt4 book ai didi

c# - 使用 TaskScheduler.FromCurrentSynchronizationContext 更新任务中的 UI

转载 作者:太空宇宙 更新时间:2023-11-03 17:53:42 24 4
gpt4 key购买 nike

我想使用 Task 将一些文本添加到列表框中,我只需使用一个按钮并在点击事件中放置以下代码:

TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 10; i++)
{
listBox1.Items.Add("Number cities in problem = " + i.ToString());
System.Threading.Thread.Sleep(1000);
}
}, CancellationToken.None, TaskCreationOptions.None, uiScheduler);

但它不起作用并且 UI 锁定直到 for 循环结束。

问题出在哪里?

谢谢:)

最佳答案

您可以在线程中完成所有工作,但是当您需要更新 UI 时使用调度程序:

Task.Factory.StartNew(() =>
{
for (int i = 0; i < 10; i++)
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(() => {listBox1.Items.Add("Number cities in problem = " + i.ToString()); }));
System.Threading.Thread.Sleep(1000);
}
});

关于c# - 使用 TaskScheduler.FromCurrentSynchronizationContext 更新任务中的 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17418208/

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