2

我正在使用 Azure ML,并且我有代码示例来调用我的 Web 服务(可惜它仅在 C# 中)。有人可以帮我把它翻译成 F# 吗?除了异步和等待之外,我已经完成了一切。

 static async Task InvokeRequestResponseService()
        {
            using (var client = new HttpClient())
            {
                ScoreData scoreData = new ScoreData()
                {
                    FeatureVector = new Dictionary<string, string>() 
                    {
                        { "Zip Code", "0" },
                        { "Race", "0" },
                        { "Party", "0" },
                        { "Gender", "0" },
                        { "Age", "0" },
                        { "Voted Ind", "0" },
                    },
                    GlobalParameters = new Dictionary<string, string>() 
                    {
                    }
                };

                ScoreRequest scoreRequest = new ScoreRequest()
                {
                    Id = "score00001",
                    Instance = scoreData
                };

                const string apiKey = "abc123"; // Replace this with the API key for the web service
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", apiKey);

                client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/workspaces/19a2e623b6a944a3a7f07c74b31c3b6d/services/f51945a42efa42a49f563a59561f5014/score");
                HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);
                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Result: {0}", result);
                }
                else
                {
                    Console.WriteLine("Failed with status code: {0}", response.StatusCode);
                }
            }

谢谢

4

1 回答 1

4

我无法编译和运行代码,但您可能需要这样的东西:

let invokeRequestResponseService() = async {
    use client = new HttpClient()
    let scoreData = (...)
    let apiKey = "abc123"
    client.DefaultRequestHeaders.Authorization <- 
        new AuthenticationHeaderValue("Bearer", apiKey)
    client.BaseAddress <- Uri("https://ussouthcentral..../score");
    let! response = client.PostAsJsonAsync("", scoreRequest) |> Async.AwaitTask
    if response.IsSuccessStatusCode then
        let! result = response.Content.ReadAsStringAsync() |> Async.AwaitTask
        Console.WriteLine("Result: {0}", result);
    else
        Console.WriteLine("Failed with status code: {0}", response.StatusCode) }
  • 将代码包装在async { .. }块中使其异步并允许您let!在块内使用以执行异步等待(即在您将await在 C# 中使用的地方)

  • F# 使用类型Async<T>而不是 .NET 任务,因此当您等待任务时,您需要插入Async.AwaitTask(或者您可以为最常用的操作编写包装器)

  • invokeRequestResponseService()函数返回 F# async,因此如果您需要将其传递给其他库函数(或者如果它需要返回任务),您可以使用Async.StartAsTask

于 2014-09-14T22:22:38.503 回答