Вопрос

So if I have 5 asynctasks running and I cancel them the UI freezes a little bit, but if I do 20 asyncTasks and cancel them then my UI freezes for a noticeable time. My question is, is the asyncTask.cancel(true) method expensive? Is that way my UI is freezing? I noticed that when I do not call cancel that my UI does not freeze. Is there anyway I can prevent my UI from freezing? I tried putting the .cancel(true) method in it's own thread, but that did not help.

Here some code.

     //could be as little as 1 or could be 20
    for( AsyncTask asyncTask : asyncTasks )
    {
        if ( asyncTask != null )
        {
            //seems to block UI for a bit if there are a lot of calls
            asyncTask.cancel( true );
        }
    }
Это было полезно?

Решение 2

After making the cancel call I was logging the object, which uses the jackson library. It re instantiated

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); 

every time I wanted to use this method. Thus, I just instantiated new ObjectMapper().writer().withDefaultPrettyPrinter(); once and it fixed the lag on the UI I was having.

Другие советы

Does your task check the isCancelled() in your doInBackground() function?

AsyncTask's are meant to run quickly (i.e. computationally short tasks) in the background and post results to the UI thread. This means that when you make a call to asyncTask.cancel(true);, instead of onPostExecute being invoked on the UI thread, onCancelled is invoked on the UI thread.

Since the 'cancelling' is invoked on the UI thread, if your thread is in a tight loop and doesn't make any checks to any global variables or cancel requests (like checking isCancelled), it might take a 'bit of time' for the underlying API to clean up your thread (properly end/cancel it without your thread ending itself), that 'bit of time' is the UI 'pause' you experience.

To alleviate this, in your doInBackground function, just make a check for the isCancelled function:

// simple example function:
protected Void doInBackground (Void... params) {
    for(int i=0; i < 65535; ++i) {
        if (isCancelled()) { break; } // exit loop on cancel request
    }
    return null;
}

In this AsyncTask if we then call asyncTask.cancel(true);, the loop will break on the next check of isCancelled and the UI thread can continue vs. waiting for the loop to finish it's iterations (thus 'pausing' the UI until the thread has completed).

Hope that can help.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top