简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM