manjusg
manjusg

Reputation: 2263

Thread.Sleep() in Asyntask Android

Does doing Thread.Sleep(10) will have any side effects on performance of Applications?

To be precise will doing Thread.Sleep(100) inside DoinBackground() method will affect other Asyntasks in the Process?

If so is there a way we can cause a delay inside Asynctask so that other Tasks executing doesn't get affected?

Thanks & Regards,

manjusg

Upvotes: 0

Views: 506

Answers (2)

kupsef
kupsef

Reputation: 3367

It depends on your android:targetSdkVersion="".

http://developer.android.com/reference/android/os/AsyncTask.html

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.

The safest way is to execute them parallel with an Executor as mentioned above, but this requires the minimum SDK of 11. An alternative solution is to check the current SDK and use executor only when available:

if (Build.VERSION.SDK_INT >= 11) {
     // use executor to achieve parallel execution
     asy.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else { 
     // this way they will execute parallel by default
     asy.execute();
}

Upvotes: 1

Arun
Arun

Reputation: 1668

YES it will affect the performance of your application. AsyncTask executes serially, so this will delay start of other AsyncTask. But still if its necessary for your app to sleep in a AsyncTask without affecting other AsyncTask you can execute them in parallel. But this also has a drawback. This will consume more memory than the default one, so if you have more number of tasks to execute you may end up in OOM. Below is how you can run your task in parallel

yourAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);

hope it will help ;)

Upvotes: 1

Related Questions