后台工作者,如何构造命令
如果我有一个方法可以执行类似的操作
if (ab)
{
//dostuff
}
else if (b)
{
//dostuff
}
else if (c)
{
//do stuff.
}
并且每个方法都会关闭当前打开的表单,并重新显示具有不同数据的新表单。我怎样才能用一个显示加载栏的表单来包装每个内容,只是为了让用户没有加载任何内容。
我无法在新线程中打开加载表单,因为进度条没有进度,而且有 3 个不同的后台工作人员执行相同的操作,这似乎很愚蠢。
谢谢
If i have a method that does something like this
if (ab)
{
//dostuff
}
else if (b)
{
//dostuff
}
else if (c)
{
//do stuff.
}
And each closes the currently open form, and redisplays a new form with different data. How can i wrap each with a form that displays a loading bar just to let the user no something is loading.
I cant open the loading form in the new thread because the progress bar doesnt progress and it seems silly ot have 3 different background workers with do work methods which al ldo the same thing .
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以轻松地将数据传递到 BackgroundWorker
然后,有:
you can easily pass data into the BackgroundWorker
and then, have:
处理
ProgressChanged 事件
更新进度条?这将在 UI 线程上运行回调。由于BackgroundWorker 通过DoWork 事件运行任务,因此在所有情况下都可以将其连接到相同的方法(或任意方法)。如果使用闭包(阅读:lambdas/anon 函数),则可以轻松保留正确的绑定。
快乐编码。
Handle the
ProgressChanged event
to update the progress bar? This will run the callback on the UI thread.Since the BackgroundWorker runs the task through the
DoWork event
, this can be wired to the same method in all cases (or to an arbitrary method). If closures (read: lambdas/anon functions) are used, the correct binding can be trivially kept about.Happy coding.
正如 balexandre 已经指出的,您可以将数据传递给 Worker。但这些数据也可以通过 Action 或 Func 来实现。因此,您可以传入应在后台工作人员中执行的任何方法。可以在此答案中找到示例。
但请注意,如果您尝试在后台工作任务中设置 gui 元素的任何属性,则可能会遇到跨线程异常。要完成此
BeginInvoke
是您的朋友,它也可以封装在 扩展方法。As balexandre already noted you can pass data to the Worker. But this data can also by an Action or Func. So you can pass in any method that should be performed in a background worker. An example can be found in this answer.
But be aware that you could run into Cross-Thread exceptions if you try to set any property of a gui element within the background worker task. To accomplish this
BeginInvoke
is your friend which can also be encapsulated in an extension method.