根据请求完成 AsyncTask
我正在创建一个游戏,用户与 GUI 交互,而计算机在后台任务中找到谜题的解决方案。用户可以选择随时结束游戏,此时我想停止后台任务并检索它找到的解决方案。
这一切都工作正常,除了当用户选择时我无法强制后台任务结束?!?当用户选择“完成”时,我会看到以下内容:
computerSolutionTask.cancel(true);
// ...disable some GUI buttons etc...
while (computerSolutionTask.getStatus() != AsyncTask.Status.FINISHED){
// ...do nothing...
}
txt_computer.setText(computerSolutionTask.get());
在我的 AsyncTask 类中,我定期检查“isCancelled()”,但它似乎挂在我上面包含的 while 循环中。
我觉得我对整个事情的处理可能有点不正确,因为我真的不想取消后台任务,我只是希望它完成并返回它所拥有的内容。
这个线程似乎在问我同样的问题,但没有解决方案...到目前为止,我的所有研究都是空白,任何帮助将不胜感激。
I am creating a game where the user interacts with the GUI while the computer finds solutions to the puzzle in a background task. The user can choose to end the game any time, at which point I want to stop my background task and retrieve the solutions it found.
This is all working fine except that I can't force the background task to end when the user chooses?!? When the user selects "Done" I have the following:
computerSolutionTask.cancel(true);
// ...disable some GUI buttons etc...
while (computerSolutionTask.getStatus() != AsyncTask.Status.FINISHED){
// ...do nothing...
}
txt_computer.setText(computerSolutionTask.get());
And in my AsyncTask class I am checking "isCancelled()" regularly but it just seems to hang in the while loop I included above.
I feel that I may be going about this whole thing a little incorrectly because I don't really want to cancel the background task I just want it to finish wherever it's up to and return what it has.
This thread appears to be asking the same question I am but has no solution...I'm drawing blanks with all my research thus far and any help would be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正在运行的
AsyncTask
被取消将永远不会到达onPostExecute
,因此它永远不会“完成”。无论如何,如果您的特定逻辑需要它使用常规同步方法,您就不需要等待它。A running
AsyncTask
that is cancelled will never reachonPostExecute
and so it will never 'finish'. You don't need to wait for it anyway, if your particular logic requires it use regular synchronization methods.您需要将条件放在 doInBackground() 方法中来检查 AsyncTask 是否已取消或处于运行状态。
You need to put the condition inside the doInBackground() method to check whether the AsyncTask is cancelled or in running state.