AsyncTask的不是异步运行 [英] AsyncTask not running asynchronously

查看:99
本文介绍了AsyncTask的不是异步运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面分别应该是,如果我没有弄错的一样。照片 使用的AsyncTask

The following were supposed to be the same if I am not mistaking.
Using AsyncTask:

private class GetDataTask extends AsyncTask<String, Void, String>{

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected String doInBackground(String... params) {
        return NetConnection.getRecordData(mUserId, mUserPassword);
    }

    @Override
    protected void onPostExecute(String result) {
        parseJson(result);
    }
}

使用的

    new Thread( new Runnable() {

        @Override
        public void run() {
            String res = NetConnection. getRecordData(mUserId, mUserPassword);
            parseJson(res);

        }
    }).start();

但上传文件时,该AsyncTask的运行同步而线程中运行异步(平行)。< BR> 为什么会这样呢?为什么AsyncTask的行为就像这样?是不是AsyncTask的应该异步运行?
我有点糊涂了,所以我需要你的帮助。
这就是我如何调用GetDataTask:

But when uploading a file, the AsyncTask runs synchronously while the Thread run asynchronously(in parallel).
Why is so? Why AsyncTask behaves like this? Isn't AsyncTask supposed to run asynchronously?
I am little confused so I need your help.
This is how I invoke the GetDataTask:

new GetDataTask().execute()

我preFER使用AsyncTask的,但它没有做的工作对我来说。请参考我的早期问题了解更多详细信息

I prefer using AsyncTask but it is not doing the job for me. Please refer to my early question for more details

推荐答案

随着4.x的调用2 AsyncTasks将导致他们要串行执行。

As of 4.x calling 2 AsyncTasks will cause them to be executed serially.

要解决这个问题的一种方法是使用下面的code

One way to fix this is using the following code

if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
  myTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
else {
  myTask.execute();
}

您可以阅读更多的:<一href="http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html">http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html

这篇关于AsyncTask的不是异步运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆