urrentSynchronizationContext任务更新

urrentSynchronizationContext任务更新

本文介绍了使用TaskScheduler.FromCurrentSynchronizationContext任务更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加一些文字使用到列表框中工作和我简单地用一个按钮,发生在click事件代码:

 的TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); 
Task.Factory.StartNew(()=>
{
的for(int i = 0;我小于10;我++)
{
listBox1.Items 。新增(问题中的一些城市=+ i.ToString());
System.Threading.Thread.Sleep(1000);
}
},CancellationToken.None,TaskCreationOptions。无,uiScheduler);



但它不工作和UI锁定直至月底循环。



问题出在哪里。



感谢:?)


解决方案

Well you're explicitly saying that you want to execute the task in the UI thread... and then you're sleeping within the task, so it's blocking the UI thread. How did you expect to be in the UI thread, but for Thread.Sleep not to cause a problem?

If you can use C# 5 and async/await, that would make things much easier:

private static async Task ShowCitiesAsync()
{
    for (int i = 0; i < 10; i++)
    {
        listBox1.Items.Add("Number cities in problem = " + i);
        await Task.Delay(1000);
    }
}

If you can't use C# 5 (as suggested by your tags), it's significantly trickier. You might be best off using a Timer:

// Note: you probably want System.Windows.Forms.Timer, so that it
// will automatically fire on the UI thread.
Timer timer = new Timer { Interval = 1000; }
int i = 0;
timer.Tick += delegate
{
    listBox1.Items.Add("Number cities in problem = " + i);
    i++;
    if (i == 10)
    {
        timer.Stop();
        timer.Dispose();
    }
};
timer.Start();

As you can see, it's pretty ugly... and it assumes you don't want to actually do any work between UI updates.

Another alternative would be to simulate your long-running task (sleeping at the moment) on a different thread using BackgroundWorker, and use ReportProgress to come back to the UI thread to add the list item.

这篇关于使用TaskScheduler.FromCurrentSynchronizationContext任务更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 08:26