jfx-asynctask icon indicating copy to clipboard operation
jfx-asynctask copied to clipboard

AsyncTask is not terminated when program close

Open hungthuanmk opened this issue 6 years ago • 0 comments

I create a simple code to stream webcam source to ImageView, but when the program close it seems that the AsyncTask was not terminated all Here is the code for my AsyncTask, i have already set thread deamon to True

public class StreamingThread extends AsyncTask {

    private boolean isPlaying = false;

    private VideoCapture vc;
    private Mat currentFrame;
    private int fps = 30;
    private ImageView imageViewer = null;

    public StreamingThread(int cameraIdx, ImageView imageViewer) {
        this.vc = new VideoCapture(cameraIdx);
        this.imageViewer = imageViewer;
        setDaemon(true);
        backGroundThread.setDaemon(true);
    }

    public void stopStream() {
        this.isPlaying = false;
    }

    public void startStream() {
        this.isPlaying = true;
        this.execute();
    }

    public void setFps(int fps) {
        this.fps = fps;
    }

    @Override
    public void onPreExecute() {
        System.out.println("Stated thread!");
    }

    @Override
    public Object doInBackground(Object[] objects) {
        currentFrame = new Mat();
        long beginTime, endTime, delay;

        while (isPlaying) {
            beginTime = System.nanoTime();
            vc.read(currentFrame);
            if (this.imageViewer != null) {
                ImageProcessing.setImage(this.imageViewer, this.currentFrame);
            }
            endTime = System.nanoTime();
            delay = (endTime - beginTime)/1000l;
            try {
                TimeUnit.MICROSECONDS.sleep(30000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public void onPostExecute(Object o) {
        vc.release();
        System.out.println("Stopping thread!");
    }

    @Override
    public void progressCallback(Object[] objects) {

    }

And here is the way i call AsyncTask in controller

streamingThread = new StreamingThread(0, imgCamFont);
streamingThread.startStream();

hungthuanmk avatar Nov 07 '18 07:11 hungthuanmk