简体   繁体   English

Android AsyncTask异常和onPostExecute

[英]Android AsyncTask exception and onPostExecute

I have two AsyncTask classes. 我有两个AsyncTask类。 First: 第一:

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

    ...
}

Second: 第二:

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

    ...
}

As you can see when NotationChanger has done his work it wakes Calculator class. 如您所见,当NotationChanger完成工作时,它将唤醒Calculator类。 It works fine while there is no an exception. 毫无例外,它工作正常。 When I get a ParseErrorException in NotationChanger class method onPostExecute isn't called. 当我在NotationChanger类中获得ParseErrorException时,不会调用onPostExecute。

If I move 如果我搬家

changedNotation = true; 

from onPostExecute function to finally block it works well every time. 从onPostExecute函数最终阻止它每次都可以正常工作。 Does it mean that exception in doInBackground breaks calling of onPostExecute method or I don't understand anything? 这是否意味着doInBackground中的异常中断了onPostExecute方法的调用,或者我什么都不懂?

If Calculator run first, and waiting in doInBackground(). 如果Calculator首先运行,然后在doInBackground()中等待。 I think that your NotationChanger can not enter doInBackground(). 我认为您的NotationChanger无法输入doInBackground()。 In my experience, all AsyncTask use only one thread to work. 以我的经验,所有AsyncTask仅使用一个线程来工作。

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

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