并行中的异步函数调用

并行中的异步函数调用

本文介绍了并行中的异步函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下版本同步调用所有函数,

Following version is calling all functions synchronously,

我正在寻找如何并行调用异步函数并将所有resultserrors返回给调用者的方法.

I'm looking to find out how to call asynchronous functions in parallel and return all results and errors to the caller.

请求

let requestAsync (url: string) : Async<Result<string, Error>> =
    async {
        Console.WriteLine ("Simulating request " + url)
        try
            do! Async.Sleep(1000)
            return Ok (url + ": body...")
        with :? WebException as e ->
            return Error {code = 500; message = "Internal Server Error";}
    }

测试

[<TestMethod>]
member this.TestrequestAsync() =
    let urls = [|
        "http://www.example.com/1";
        "http://www.example.com/2";
        "http://www.example.com/3";
        "http://www.example.com/4";
        "http://www.example.com/5";
        "http://www.example.com/6";
        "http://www.example.com/7";
        "http://www.example.com/8";
        "http://www.example.com/9";
        "http://www.example.com/10";
    |]

    urls
    |> Array.map (fun url -> requestAsync url |> Async.RunSynchronously) // Async.Parallel some mismatch

    // Iterate results

理想情况下,可以在遍历结果的同时匹配OkError结果

Ideally to be able to match Ok and Error results while iterating through results

编辑.

let result =
    urls
    |> Seq.map Entity.requestDetailAsync2
    |> Async.Parallel
    |> Async.RunSynchronously


result
|> Array.iter Console.WriteLine // match x with Ok and Error?

尝试

result |> Array.iter (fun data -> match data with
                                      | Ok result -> Console.WriteLine(result)
                                      | Error error -> Console.WriteLine(error) )

使用For in

for r in result do
    match r with
    | Ok re -> Console.WriteLine(re)
    | Error error -> Console.WriteLine(error)

推荐答案

您可以使用Async.Parallel并行运行许多异步操作:

You can use Async.Parallel to run many async operations in parallel:

let results =
  urls
  |> Seq.map requestAsync   // seq<Async<'T>>
  |> Async.Parallel         // async<T' []>
  |> Async.RunSynchronously // T' []

这是一个非常相似的示例在MSDN上.

您的requestAsync函数返回类型可能有问题,或者示例中缺少类型定义.这是我用来验证解决方案的内容:

There may be an issue with your requestAsync function return type, or a missing type definition in your example. Here's what I used to verify the solution:

type RequestError = {
  code : int
  message : string
}

let requestAsync (url: string) =
    async {
        Console.WriteLine ("Simulating request " + url)
        try
            do! Async.Sleep(1000)
            return Ok (url + ": body...")
        with :? WebException as e ->
            return Error {code = 500; message = "Internal Server Error";}
    }

这篇关于并行中的异步函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 21:58