[英]Wpf Dispatcher Pause and Continue
I have a list view that is bound to a collection. 我有一个绑定到集合的列表视图。
The collection is updated using the dispatcher.current dispatcher so that the items get added incrementally to the list view. 使用dispatcher.current调度程序更新该集合,以便将项目逐步添加到列表视图中。
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
if(continueDispatcher)numDone = DoStuff();
}));
This works really well, and the continueDispatcher flag stops the thread dead in its tracks, which is cool, but I would like to be able to continue the dispatcher operations on a button click. 这确实非常有效,并且continueDispatcher标志将线程停止在其轨道中,这很酷,但是我希望能够通过单击按钮来继续调度程序操作。
I have read about dispatcher frames and the like but I dont seem to be able to find a solution that works. 我已经阅读了有关调度程序框架之类的信息,但似乎无法找到有效的解决方案。
Has anyone got any ideas on this issue? 有没有人对这个问题有任何想法?
Edit - More Code 编辑-更多代码
//for each image
foreach (var result in results)
{
result.Type = type;
numDone = LoadImagesAsync(result, numDone, total);
}
private int LoadImagesAsync(Item result, int numDone, int total)
{
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
//keep looping
while (true)
{
//if the dispatcher is paused then continue the loop
if (DispatcherPaused) continue;
//if the dispatcher is not paused then perform the action and break out of the loop
numDone = DoStuff(result, numDone, total);
break;
}
}));
return numDone;
}
private int DoStuff(Item result, int numDone, int total)
{
ItemList.Add(result);
numDone++;
ProgressBarValue = ((double) numDone/total)*100;
return numDone;
}
Thread t = new Thread(() =>
{
while (true)
{
if (continueDispatcher)
numDone = DoStuff();
Thread.Sleep(50);
}
});
t.Start();
First, you should never block/monopolize the UI thread like this. 首先, 永远不要像这样阻塞/独占UI线程。 Find some other way to manage a long-running, interruptable task.
寻找其他方法来管理长期运行的可中断任务。 If possible, use a
BackgroundWorker
and do the bulk of the work on another thread, while marshaling back to the UI thread to report progress and commit your results (either a little at a time, or all at once). 如果可能,请使用
BackgroundWorker
并在另一个线程上进行大量工作,同时编组回UI线程以报告进度并提交结果(一次或一次全部提交)。
Also, if you want to 'pause' an operation, you shouldn't just busy-wait in a loop. 同样,如果您想“暂停”操作,则不应只是忙于循环等待。 That will send your CPU usage through the roof.
这将使您的CPU使用率急剧上升。 In general, you should use some sort of wait handle to send the thread into a waiting state until you notify it to resume (but never do this to the UI thread).
通常,您应该使用某种等待句柄将线程发送到等待状态,直到您通知它恢复(但不要对UI线程执行此操作)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.