How do I wait until Task is finished in C#?

后端 未结 6 870
孤街浪徒
孤街浪徒 2020-12-04 23:49

I want to send a request to a server and process the returned value:

private static string Send(int id)
{
    Task responseTask =          


        
6条回答
  •  有刺的猬
    2020-12-05 00:38

    I'm an async novice, so I can't tell you definitively what is happening here. I suspect that there's a mismatch in the method execution expectations, even though you are using tasks internally in the methods. I think you'd get the results you are expecting if you changed Print to return a Task:

    private static string Send(int id)
    {
        Task responseTask = client.GetAsync("aaaaa");
        Task result;
        responseTask.ContinueWith(x => result = Print(x));
        result.Wait();
        responseTask.Wait(); // There's likely a better way to wait for both tasks without doing it in this awkward, consecutive way.
        return result.Result;
    }
    
    private static Task Print(Task httpTask)
    {
        Task task = httpTask.Result.Content.ReadAsStringAsync();
        string result = string.Empty;
        task.ContinueWith(t =>
        {
            Console.WriteLine("Result: " + t.Result);
            result = t.Result;
        });
        return task;
    }
    

提交回复
热议问题