我想通过队列迭代 - 从队列中取1项,在后台任务中处理它,更新UI,然后取下一个项目,依此类推。问题是第一个项目在后台任务(线程)中处理,但随后的项目在UI线程中处理 - 阻止UI。递归任务队列
有谁知道为什么发生这种情况,以及如何解决这个问题?我的完整测试代码如下。注意:这段代码是为了我的学习和将来的参考 - 不是任何真实的应用程序。
public partial class MainWindow : Window
{
private Queue<int> testQueue = new Queue<int>();
private TaskScheduler uiScheduler;
public MainWindow()
{
InitializeComponent();
this.uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
this.testQueue = new Queue<int>();
this.testQueue.Enqueue(3);
this.testQueue.Enqueue(6);
this.testQueue.Enqueue(7);
this.testQueue.Enqueue(11);
this.testQueue.Enqueue(13);
}
// just a method that takes about 1 second to run on a modern pc
private double SumRootN(int root)
{
double result = 0;
for (int i = 1; i < 10000000; i++)
{
result += Math.Exp(Math.Log(i)/root);
}
return result;
}
private void testQueueButton_Click(object sender, RoutedEventArgs e)
{
this.processQueue();
}
private void processQueue()
{
if (this.testQueue.Count > 0)
{
int root = this.testQueue.Dequeue();
Task<double>.Factory.StartNew(() => SumRootN(root))
.ContinueWith(t =>
{
this.statusText.Text += String.Format("root {0} : {1}\n", root, t.Result);
this.processQueue();
}, uiScheduler);
}
else
{
this.statusText.Text += "Done\n";
}
}
}
非常感谢!我错误地假设了。 – flolim
我也是。我调试了这个,因为我无法相信它。 – usr