繁体   English   中英

Android AsyncTask异常和onPostExecute

[英]Android AsyncTask exception and onPostExecute

我有两个AsyncTask类。 第一:

private class NotationChanger extends AsyncTask <Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        synchronized(mutex) {
            try {
                this.infixToPostNotation();
            } catch(ParseErrorException e) {
                Log.i("Parse Error Exception", e.getMessage());
                changedNotationError = true;
            }
            finally {
                mutex.notify();                         //Calculator waits while notation is being changed
            }                                           //So we should wake it                      
        }
        return null;
    }


    @Override 
    protected void onPreExecute() {
        super.onPreExecute();
        changedNotation = false;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        changedNotation = true;
    } 

    ...
}

第二:

private class Calculator extends AsyncTask <Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... arg0) {
        synchronized(mutex) {
            while(!changedNotation) {
                try {
                    mutex.wait();
                }   catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        Log.i("Calculation", "waked");

        if(!changedNotationError) {
            try {
                this.calculatePoints();
            } catch (CalculateException e) {
                Log.i("Calculate exception", e.getMessage());
            }
        }
        else {
            changedNotationError = false;
        }

        return null;
    }

    ...
}

如您所见,当NotationChanger完成工作时,它将唤醒Calculator类。 毫无例外,它工作正常。 当我在NotationChanger类中获得ParseErrorException时,不会调用onPostExecute。

如果我搬家

changedNotation = true; 

从onPostExecute函数最终阻止它每次都可以正常工作。 这是否意味着doInBackground中的异常中断了onPostExecute方法的调用,或者我什么都不懂?

如果Calculator首先运行,然后在doInBackground()中等待。 我认为您的NotationChanger无法输入doInBackground()。 以我的经验,所有AsyncTask仅使用一个线程来工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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