【问题标题】:calling AsyncTask in main thread inside a for loop在 for 循环内的主线程中调用 AsyncTask
【发布时间】:2015-05-19 04:23:02
【问题描述】:

我有 someclass 进行大型网络操作,它确实需要一些时间才能完成,因此我把它放在AsyncTask 中。我必须做这个过程'n'次,所以在使用for 循环的主线程我调用了这个asynctask n 次。由于完成for 循环时出现中断,它会抛出任何错误吗?

// inside main thread 
for(i=0;i<n;i++)
{
 new asynctask().execute(new someclass());
}

【问题讨论】:

  • 不要尝试这个......将你的循环运行到异步任务中......
  • 如果不行我得改很多方法,你确定不行吗?
  • 你的意思是“完成for循环有中断”?
  • 这需要时间,这就是我的意思..
  • 如果for循环是异步的,怎么会有超时?

标签: java android multithreading android-asynctask


【解决方案1】:

不推荐运行多个AsyncTask,但如果是几次,那么它会工作,但所有异步任务将串行运行而不是并行运行。但是,如果您希望异步任务并行运行,那么您可以调用它的 executeOnExecutor(..) 方法,您必须将 THREAD_POOL_EXECUTOR 作为参数传递。你可以在google上搜索,你可以找到很多链接。 Here 是您帮助的示例。

【讨论】:

  • okke 让我试试,如果它不起作用,我会照你说的做......谢谢
【解决方案2】:

不要调用 AsyncTask n 次,只需将你的 for 循环放入 onPostExecute() 并执行最多 n 次的任何任务

    private class AsyncTaskRunner extends AsyncTask<String, String, String> {



      @Override
      protected String doInBackground(String... params) {

       } catch (Exception e) {
        e.printStackTrace();
       }
       return resp;
      }


      @Override
      protected void onPostExecute(String result) {
       // execution of result of Long time consuming operation

   for(i=0;i<n;i++)
    {
    //do your operation here
    }

      }


      @Override
      protected void onPreExecute() {
       // Things to be done before execution of long running operation. For
       // example showing ProgessDialog
      }


      @Override
      protected void onProgressUpdate(String... text) {

       // Things to be done while execution of long running operation is in
       // progress. For example updating ProgessDialog



      }
     }
    }

【讨论】:

    猜你喜欢
    • 2020-01-11
    • 2022-07-07
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 2011-08-20
    相关资源
    最近更新 更多