要强制取消 AsyncTask,doInBackground 中定期检查的标志不应该是易变的吗?

To force cancel AsyncTask shouldn't the flag periodically checked in doInBackground be volatile?

我想强制取消AsyncTask。我看到您可以使用 isCancelled() like in this valid solution (which under the hood uses AtomicBoolean.

但我看到像 suspiciousSolution1, suspiciousSolution2, suspiciousSolution3 这样的解决方案,其中引入了新标志 private boolean isTaskCancelled = false;

我开始怀疑 - 因为那个标志在

中被修改了
public void cancelTask(){
   isTaskCancelled = true;
}

在某个线程上运行,并被读入

protected Void doInBackground( Void... ignoredParams ) {
    //Do some stuff
    if (isTaskCancelled()){
        return;
    }
}

它在 WorkerThread, then shouldn't the flag isTaskCancelled be volatile (or AtomicBoolean 中运行,就像在 Google 的实现中一样)。

是的,不稳定。考虑到您只是使用它来定期检查您的异步任务。如果它是多个线程,我会建议使用原子字段。请在此处查看更多信息:volatile vs atomic & Volatile boolean vs AtomicBoolean

对,应该是volatile。否则,由于优化(通过编译器、JVM 等),线程 A 中的变量写入可能对线程 B 中的读取不可见。参见 this

试试这个

Initialize

  private AysncTask aysncTask;

Task Call

   aysncTask=new AysncTask();
        aysncTask.execute();

Task Cancel Where You WANT

  if ( aysncTask != null && aysncTask.getStatus() == aysncTask.Status.RUNNING ){
        aysncTask.cancel(true);

    }