Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用Scala';如何超时多个异步请求;什么是异步的?_C#_Scala_Asynchronous_Go - Fatal编程技术网

C# 使用Scala';如何超时多个异步请求;什么是异步的?

C# 使用Scala';如何超时多个异步请求;什么是异步的?,c#,scala,asynchronous,go,C#,Scala,Asynchronous,Go,我不知道Scala,但我很好奇它的异步特性(类似于C#)。如何将这段go代码转换为Scala async c:=make(更改结果) go func(){c这里是一个如何实现的示意图(未经测试;我不认为这是最好的解决方案): //我假设Web/Image/Video函数返回Future[Result]的实例 val f1=Web(查询) val f2=图像(查询) val f3=视频(查询) val t=超时(80毫秒) //使用Scala未来的API val结果:未来[顺序[结果]]=for

我不知道Scala,但我很好奇它的异步特性(类似于C#)。如何将这段go代码转换为Scala async

c:=make(更改结果)

go func(){c这里是一个如何实现的示意图(未经测试;我不认为这是最好的解决方案):

//我假设Web/Image/Video函数返回Future[Result]的实例
val f1=Web(查询)
val f2=图像(查询)
val f3=视频(查询)
val t=超时(80毫秒)
//使用Scala未来的API
val结果:未来[顺序[结果]]=for{

您指的是r1吗?请注意,Scala本身和标准库都没有
async
功能。是的,这就是我指的库。
c := make(chan Result)
go func() { c <- Web(query) } ()
go func() { c <- Image(query) } ()
go func() { c <- Video(query) } ()

timeout := time.After(80 * time.Millisecond)
for i := 0; i < 3; i++ {
    select {
    case result := <-c:
        results = append(results, result)
    case <-timeout:
        fmt.Println("timed out")
        return
    }
}
return
// I assume that the Web/Image/Video functions return instances of Future[Result]
val f1 = Web(query)
val f2 = Image(query)
val f3 = Video(query)
val t = timeout(80.milliseconds)

// using Scala's Future API
val results: Future[Seq[Result]] = for {
  r1 <- or(f1)(t)
  r2 <- or(f2)(t)
  r3 <- or(f3)(t)
} yield (r1.toSeq ++ r2.toSeq ++ r3.toSeq)

// OR using async
val results: Future[Seq[Result]] = async {
  val r1 = or(f1)(t)
  val r2 = or(f2)(t)
  val r3 = or(f3)(t)
  await(r1).toSeq ++ await(r2).toSeq ++ await(r3).toSeq
}

// or and timeout are utility/library functions defined below

def or[T](f1: Future[T])(f2: Future[Option[Nothing]]): Future[Option[T]] =
  Future.firstCompletedOf(f1 map Some.apply, f2)

// create a future that will complete successfully with None
// after the given duration passes
def timeout(d: Duration): Future[Option[Nothing]] = {
  val p = Promise[Option[Nothing]]
  Scheduler.after(d) { p success None }
  p.future
}