BackGroundWorker 的问题
我使用 BackGroundWorker 来避免 UI 冻结,同时使用使用等待句柄的方法,并且此方法用于在 UI 中的面板上进行绘制,并具有 <内部面板失效。
something()
{
draw()
panel.invalidate()
A.waitone(500)
}
问题是,有时工作人员会卡在绘图中间,当我重新按下工作人员启动按钮时,它会再次工作并且不会卡住,这意味着它没有因为忙碌而卡住,所以绘图被卡住的不是工人,但我每次抽奖后都会失效,所以有什么想法吗?
I'm using a BackGroundWorker to avoid UI freezing while working with a method which uses wait handles, and this method is used to draw on a panel in the UI and has panel invalidation inside.
something()
{
draw()
panel.invalidate()
A.waitone(500)
}
The problem is, sometimes the Worker gets stuck in the middle of the drawing and when I re press the worker start button it works again and doesn't get stuck, that means it wasn't stuck due to being busy, so the drawing which got stuck not the Worker, but I have invalidation after each draw, so any ideas??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您希望后台进程更新 UI,则需要使用控件的“Invoke”方法(这将确保代码在 UI 线程中运行,而不是在后台线程中运行):
或者,无需 Lambda
编辑:在看到其他答案的新评论后 - 您可以在线程处理期间将每个控制调用包装在“Invoke”调用中,因此不要在调用中调用“draw()”方法本身,而是使用draw()方法每当需要更新 UI 时就使用 Invoke。
If you want the background process to update the UI, you need to use the control's "Invoke" method (this will ensure that the code is run in the UI thread, and not in the background thread):
Or, without the Lambda
EDIT: after seeing new comment on other answer -- you could wrap each an every control call in an 'Invoke' call during your threaded processing, so instead of calling the 'draw()' method itself in the invoke, have the draw() method use the Invoke whenever it needs to update the UI.
您不应该通过后台工作者调用的方法访问 UI 元素。
(来自评论)
如果你想一步一步地绘制,在每个步骤之间延迟,那么我倾向于使用 System.Windows.Forms.Timer 而不是等待一个等待句柄。将计时器设置为以您想要的频率触发,当它触发时,会绘制更多您正在绘制的内容。
You should not be accessing UI elements from a method called from a backgroundworker.
(From comments)
If you want to draw step by step, delaying between each step, then I'd be inclined to use a System.Windows.Forms.Timer rather than waiting on a waithandle. Set the timer to fire at the frequency you want, and when it fires draw a bit more of whatever it is you're drawing.