WP7 为两个 BackgroundWorker 对象触发一个 RunWorkerCompleted 事件
我有一些继承自 BaseOperation 类的对象。其中包括 IntializeOperation、SignOnOperation、SignOffOperation 等。BaseOperation
类具有 Execute() 方法,该方法使用 BackgroundWorker 执行任务,包括进行服务调用。我意识到这可能不是最好的设计,但这就是我现在正在使用的设计,并且现在重新设计是不可行的。这是该类的简化版本。
public void AsyncExecute()
{
_result = DoOperation();
}
public void Execute()
{
_worker = new BackgroundWorker();
_worker.WorkerReportsProgress = false;
_worker.DoWork += (s, e) =>
{
AsyncExecute();
};
_worker.RunWorkerCompleted += (s, e) =>
{
//Tell our callback what we've done
if (_result is Exception)
Failed(_result as Exception);
else
Succeeded(_result);
};
_worker.RunWorkerAsync();
}
如果我调用一项操作,它就可以正常工作。但是,如果我快速连续调用两个操作,就会遇到问题。
当第一个操作完成时,它会调用 RunWorkerCompleted 两次,每个操作调用一次。我知道,因为我可以在 RunWorkerCompleted 委托内部设置断点,它会被命中两次,而且我还可以检查要执行哪个操作,以确认每次调用它时它处于不同的操作中。我可以在第二个操作的 DoOperation() 方法中设置断点,以确认即使在该操作的 RunWorkerCompleted 事件触发后它仍然继续运行。
我无法弄清楚为什么当只有第一个操作完成时,两个操作都会引发 RunWorkerCompleted 事件。
I have a few objects that inherit from a BaseOperation class. These include IntializeOperation, SignOnOperation, SignOffOperation, etc.
The BaseOperation class has an Execute() method that uses a BackgroundWorker to do tasks, including making service calls. I realize this is probably not the best design, but it's what I'm working with right now and redesigning isn't feasible right now. Here is a simplified version of the class.
public void AsyncExecute()
{
_result = DoOperation();
}
public void Execute()
{
_worker = new BackgroundWorker();
_worker.WorkerReportsProgress = false;
_worker.DoWork += (s, e) =>
{
AsyncExecute();
};
_worker.RunWorkerCompleted += (s, e) =>
{
//Tell our callback what we've done
if (_result is Exception)
Failed(_result as Exception);
else
Succeeded(_result);
};
_worker.RunWorkerAsync();
}
If I call one operation it works fine. However, if I call two Operations in quick succession, I run into problems.
When the first operation finishes, it calls RunWorkerCompleted twice, once for each operation. I know because I can breakpoint inside the RunWorkerCompleted delegate, it gets hit twice, and I can also check which operation I'm to confirm that it is in different operations each time it is called. I can breakpoint in the 2nd operation's DoOperation() method to confirm that it continues running even after the RunWorkerCompleted event fires for that operation.
I'm having trouble figuring out why the RunWorkerCompleted event is raised for both operations when only the first operation has completed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发现了问题所在。我在 DoOperation() 方法中使用 ManualResetEvent。如果两个操作同时进行,它认为一切都已完成。
I figured out the problem. I'm using ManualResetEvent in the DoOperation() method. If two operations are going at the same time, it thinks everything has completed.