从后台工作者返回
我正在从事后台工作。这就是我需要做的:从后台工作人员返回,以便它返回到程序的主线程。我正在使用 Windows 窗体应用程序,在取消后台工作程序后,应将控制权交还给窗体,以便我可以再次调用相同的函数。
我添加了示例代码,因为我在 while 循环内使用的代码非常大。
void funtion1()
{
while(true)
{
if(backgroundWorker1->CancellationPending)
{
e->Cancel = true;
return ;
}
}
}
注意:目前,当我在停止函数后执行相同的工作时,会返回 System.NullReferenceException 我还注意到我的 DOWORK() 事件工作正常。
我需要的是通过 backgroundWorker1->CancelAsync();
停止后台工作线程,并使用 backgroundWorker1->RunWorkerAsync();
再次启动相同的函数。
但是,当我使用后台工作程序调用相同的函数时,系统会抛出 System.NullReferenceException 。
为什么会抛出 System.NullReferenceException 以及如何解决此问题?
I am working on background workers. This is what I need to do: return from a background worker so it returns to the main thread of the program. I am using a windows form application and after canceling the background worker the control should be given back to the form so I can call the same function again.
I have added sample code since the code that I am using inside the while loop is pretty large.
void funtion1()
{
while(true)
{
if(backgroundWorker1->CancellationPending)
{
e->Cancel = true;
return ;
}
}
}
Note: Currently when I do the same job after stopping the function this returns a System.NullReferenceException
I have also noted that my DOWORK() event works fine.
What I require is to stop the background worker by backgroundWorker1->CancelAsync();
and to start the same function again using backgroundWorker1->RunWorkerAsync();
.
However, when I call the same function with the background worker, the system throws a System.NullReferenceException
.
Why are System.NullReferenceException
s being thrown and how can I fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
后台线程独立于启动它的线程运行。主线程将在启动另一个线程后立即继续。
如果您想在后台工作完成时执行某些操作,可以处理 WorkerCompleted 事件。
另外,您的代码不正确。
DoWork 事件处理程序中的代码将侦听 CancelationPending。主线程在 BW 上调用 Cancel,从而设置 CancelationPending。
您应该在这里阅读 BW:http://msdn.microsoft.com/ en-us/library/8xs8549b.aspx
A background thread runs independantly of the thread that started it. The main thread will continue immediately after starting the other thread.
If you want to do something when the background worker completes, you can handle the WorkerCompleted event.
Also, your code is incorrect.
The code in your DoWork event handler will listen for CancelationPending. The main thread calls Cancel on the BW which sets CancelationPending.
You should read up on the BW here: http://msdn.microsoft.com/en-us/library/8xs8549b.aspx