鉴于:
构建.sbt
scalaVersion := "2.13.2"
libraryDependencies += "org.typelevel" %% "cats-effect" % "2.1.3"
src/main/scala/net/Main.scala
package net
import cats.effect._
import cats.implicits._
import java.util.concurrent.TimeUnit
import scala.concurrent.duration._
object App extends IOApp { self: IOApp =>
override def run(args: List[String]): IO[ExitCode] =
for {
_ <- uncancellable
_ <- notUncancellable
} yield ExitCode.Success
private def uncancellable: IO[Unit] = {
val tick: IO[Unit] = Concurrent[IO].uncancelable(self.timer.sleep(10.seconds))
for {
_ <- IO(println("uncancellable"))
fiber <- Concurrent[IO].start(tick)
_ <- IO(println("seconds begin: " + FiniteDuration.apply(System.nanoTime(), TimeUnit.NANOSECONDS).toSeconds))
_ <- fiber.cancel
_ <- fiber.join
_ <- IO(println("seconds done : " + FiniteDuration.apply(System.nanoTime(), TimeUnit.NANOSECONDS).toSeconds))
} yield ()
}
private def notUncancellable: IO[Unit] = {
val tick: IO[Unit] = self.timer.sleep(10.seconds)
for {
_ <- IO(println("notUncancellable"))
fiber <- Concurrent[IO].start(tick)
_ <- IO(println("seconds begin: " + FiniteDuration.apply(System.nanoTime(), TimeUnit.NANOSECONDS).toSeconds))
_ <- fiber.cancel
_ <- fiber.join
_ <- IO(println("seconds done : " + FiniteDuration.apply(System.nanoTime(), TimeUnit.NANOSECONDS).toSeconds))
} yield ()
}
}
运行它会显示以下输出:
sbt:cats-effect-cancellation-question> run
[info] Compiling 1 Scala source to /Users/kevinmeredith/Workspace/cats-effect-cancellation-questions/target/scala-2.13/classes ...
[info] Done compiling.
[info] Packaging /Users/kevinmeredith/Workspace/cats-effect-cancellation-questions/target/scala-2.13/cats-effect-cancellation-question_2.13-0.1.jar ...
[info] Done packaging.
[info] Running net.App
uncancellable
seconds begin: 303045
seconds done : 303055
notUncancellable
seconds begin: 303055
^C$
请注意,大约 30 秒后,我取消了它。
为什么没有"seconds done :
打印出来:
notUncancellable
seconds begin: 303055
^C$
?