取消Scala中的未来和承诺 [英] Cancellation with Future and Promise in Scala

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

问题描述

这是对我之前的问题的跟踪。

假设我有一个任务,该任务执行 interruptible 阻塞调用。我想将其作为 Future 来运行,并使用 failure 方法将取消 code> Promise 。

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.

我希望取消的工作方式如下:

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中的未来和承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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