BackGroundWorker 的问题

发布于 2024-09-07 02:28:27 字数 318 浏览 3 评论 0原文

我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

望笑 2024-09-14 02:28:27

如果您希望后台进程更新 UI,则需要使用控件的“Invoke”方法(这将确保代码在 UI 线程中运行,而不是在后台线程中运行):

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

或者,无需 Lambda

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

编辑:在看到其他答案的新评论后 - 您可以在线程处理期间将每个控制调用包装在“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):

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.

秋日私语 2024-09-14 02:28:27

您不应该通过后台工作者调用的方法访问 UI 元素。

(来自评论)

我正在尝试逐步绘制一些东西,这就是我需要等待句柄的原因

如果你想一步一步地绘制,在每个步骤之间延迟,那么我倾向于使用 System.Windows.Forms.Timer 而不是等待一个等待句柄。将计时器设置为以您想要的频率触发,当它触发时,会绘制更多您正在绘制的内容。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文