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

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

    It waits for client.GetAsync("aaaaa");, but doesn't wait for result = Print(x)

    Try responseTask.ContinueWith(x => result = Print(x)).Wait()

    --EDIT--

    Task responseTask = Task.Run(() => { 
        Thread.Sleep(1000); 
        Console.WriteLine("In task"); 
    });
    responseTask.ContinueWith(t=>Console.WriteLine("In ContinueWith"));
    responseTask.Wait();
    Console.WriteLine("End");
    

    Above code doesn't guarantee the output:

    In task
    In ContinueWith
    End
    

    But this does (see the newTask)

    Task responseTask = Task.Run(() => { 
        Thread.Sleep(1000); 
        Console.WriteLine("In task"); 
    });
    Task newTask = responseTask.ContinueWith(t=>Console.WriteLine("In ContinueWith"));
    newTask.Wait();
    Console.WriteLine("End");
    

提交回复
热议问题