在 Scala 中使用 Future 和 Promise 取消 [英] Cancellation with Future and Promise in Scala

查看:33
本文介绍了在 Scala 中使用 Future 和 Promise 取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对我之前的问题的跟进.

假设我有一个任务,它执行一个 interruptible 阻塞调用.我想将它作为 Future 运行,并使用 Promisefailure 方法取消它.

Suppose I have a task, which executes an interruptible blocking call. I would like to run it as a Future and cancel it with failure method of Promise.

我希望 cancel 按如下方式工作:

I would like the cancel to work as follows:

  • 如果在任务完成之前取消我希望任务立即"完成,如果它已经开始并且我中断阻塞调用希望 Future 调用 onFailure.

  • If one cancels the task before it finished I would like the task to finish "immediately", interrupting the blocking call if it has already started and I would like the Future to invoke onFailure.

如果一个取消任务在任务完成后我想得到一个状态,说取消失败,因为任务已经完成.

If one cancels the task after the task finished I would like to get a status saying that the cancel failed since the task already finished.

有意义吗?是否可以在 Scala 中实现?有没有此类实现的示例?

Does it make sense? Is it possible to implement in Scala? Are there any examples of such implementations?

推荐答案

scala.concurrent.Future 是只读的,因此一个读者不能为其他读者搞砸.

scala.concurrent.Future is read-only, so one reader cannot mess things up for the other readers.

看起来您应该能够实现您想要的内容,如下所示:

It seems like you should be able to implement what you want as follows:

def cancellableFuture[T](fun: Future[T] => T)(implicit ex: ExecutionContext): (Future[T], () => Boolean) = {
  val p = Promise[T]()
  val f = p.future
  p tryCompleteWith Future(fun(f))
  (f, () => p.tryFailure(new CancellationException))
}

val (f, cancel) = cancellableFuture( future => {
  while(!future.isCompleted) continueCalculation // isCompleted acts as our interrupted-flag

  result  // when we're done, return some result
})

val wasCancelled = cancel() // cancels the Future (sets its result to be a CancellationException conditionally)

这篇关于在 Scala 中使用 Future 和 Promise 取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆