根据请求完成 AsyncTask

发布于 2024-12-08 03:29:12 字数 715 浏览 0 评论 0原文

我正在创建一个游戏,用户与 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 技术交流群。

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

发布评论

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

评论(2

只涨不跌 2024-12-15 03:29:12

正在运行的 AsyncTask 被取消将永远不会到达 onPostExecute,因此它永远不会“完成”。无论如何,如果您的特定逻辑需要它使用常规同步方法,您就不需要等待它。

A running AsyncTask that is cancelled will never reach onPostExecute 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.

╭ゆ眷念 2024-12-15 03:29:12

您需要将条件放在 doInBackground() 方法中来检查 AsyncTask 是否已取消或处于运行状态。

 protected Object doInBackground(Object... x) 
    { 
        while (/* condition */)
        {

        // work...

        if (isCancelled())  break;

        } return null; }

You need to put the condition inside the doInBackground() method to check whether the AsyncTask is cancelled or in running state.

 protected Object doInBackground(Object... x) 
    { 
        while (/* condition */)
        {

        // work...

        if (isCancelled())  break;

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