barnie82
barnie82

Reputation: 161

Troubles trying to start two asynchronous tasks.

I want to start two Async Tasks but the second will not start until the first has completed.

From what I've googled, people usually suggest this approach:

new MyAsyncTask().execute(params);
new MyAsyncTask().execute(params);

However, I need to instantiate them separately and also keep the handles of the task's (to pass messages for example). Therefore, I SORT OF do this:

onStart() 
{
  taskA = new MyAsyncTask(paramsA);
  taskB = new MyAsyncTask(paramsB);
}

onButtonPress()
{
  taskA.execute();
  taskB.execute();
}

Edit: I've noticed that taskB does not actually start executing until taskA completes (which runs a tcp/ip server so it takes a long time). I cannot figure out why. Any thoughts or comments ?

Upvotes: 1

Views: 413

Answers (1)

Todd Sjolander
Todd Sjolander

Reputation: 1569

The short answer is that, depending on your version of Android, all AsyncTask subclasses may be using the same thread, so you can only do one at a time. There are two ways around this:

  1. Use Runnable instead of AsyncTask
  2. Replace one call to execute with executeOnExecutor(Executor.THREAD_POOL_EXECUTOR, params)

Clearly, try #2 first - it's less of a code change. But if that doesn't work pretty quickly, I'd switch to #1. In that case, you don't have to worry about how Android might change in the future.

If you want more details about the threading model for AsyncTask, have a look at the Android doc entry.

Upvotes: 2

Related Questions