When the worker thread works, UI becomes choppy

前端 未结 3 1699
野的像风
野的像风 2020-12-31 12:28

I have a handwriting recognition app - the user draws with their finger, the app recognizes characters. The recognition engine runs in a worker thread that has the the minim

3条回答
  •  执念已碎
    2020-12-31 13:09

    Had same problem, so I made my thread:

    1. Thread.yield() after processing a chunk of work.

    2. Limited updates posted to UI thread with a min 500 ms interval (causing much less re-draw).

    3. Made the worker work on prioritized buckets of data, this focuses on updating the views, user is currently interacting with.

    Now the whole UI is really lazy, but free of lag.

    Here's what my worker's scheduling method looks like (actual work is done by Process method):

    //--low priority
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
    
    //--as long as there's more work to do, and not cancelled--
    while (mPriorityBuffer.hasNext() && !isCancelled()) {
    
        //--get the work with highest priority--
        Work next = mPriorityBuffer.getNext();
    
        //--do work--
        Update u = mProcessor.process(next);
    
        // collect updates for main thread
        mUpdates.push(u);
    
        long timeNow = Calendar.getInstance().getTimeInMillis();
        if(timeNow - timeLast > 500){
            //--its been quite a while now, update ui--
            postUpdatesToMainThread();
            timeLast = timeNow;
        }
    
        //--let UI thread work on updates--
        Thread.yield();
    }
    

提交回复
热议问题