0

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

manjusg
  • 2,275
  • 1
  • 22
  • 31
  • 1
    http://stackoverflow.com/questions/12159403/executing-multiple-asynctasks-parallely make your async tasks run in parallel. They will then sleep independantly of each other. If you run them in serial order (which is the default behavior now) you would delay all other tasks in your entire app. – zapl Dec 07 '13 at 16:29
  • To understand `sleep()`, you must understanding threading. `sleep` should not be used just to cause a delay. There are plenty of threading methods to cause code to pause and execute at a later time such as `postDelayed()`. `sleep()` is used to yield processing resources to the CPU so that it will not time slice (or multitask) your thread when you do not need it to execute. For example, you are waiting for a deadlock to resolve. – Simon Dec 07 '13 at 16:44

2 Answers2

1

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 ;)

Arun
  • 1,658
  • 1
  • 14
  • 21
1

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();
}
kupsef
  • 3,357
  • 1
  • 21
  • 31