开发者

Problem with BackGroundWorker

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??


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):

something()
{
  panel.Invoke(new Action( () => {this.draw(); panel.Invalidate();} );
  A.waitone(500)
}

Or, without the Lambda

something()
{
  panel.Invoke((MethodInvoker)delegate{ this.draw(); panel.Invalidate();});
  A.waitone(500)
}

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.


You should not be accessing UI elements from a method called from a backgroundworker.

(From comments)

I'm trying to draw something step by step that's why I need the waithandles

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜