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

后端 未结 6 889
孤街浪徒
孤街浪徒 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:50

    Your Print method likely needs to wait for the continuation to finish (ContinueWith returns a task which you can wait on). Otherwise the second ReadAsStringAsync finishes, the method returns (before result is assigned in the continuation). Same problem exists in your send method. Both need to wait on the continuation to consistently get the results you want. Similar to below

    private static string Send(int id)
    {
        Task responseTask = client.GetAsync("aaaaa");
        string result = string.Empty;
        Task continuation = responseTask.ContinueWith(x => result = Print(x));
        continuation.Wait();
        return result;
    }
    
    private static string Print(Task httpTask)
    {
        Task task = httpTask.Result.Content.ReadAsStringAsync();
        string result = string.Empty;
        Task continuation = task.ContinueWith(t =>
        {
            Console.WriteLine("Result: " + t.Result);
            result = t.Result;
        });
        continuation.Wait();  
        return result;
    }
    

提交回复
热议问题