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

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

    async Task AccessTheWebAsync()  
    {   
        // You need to add a reference to System.Net.Http to declare client.  
        HttpClient client = new HttpClient();  
    
        // GetStringAsync returns a Task. That means that when you await the  
        // task you'll get a string (urlContents).  
        Task getStringTask = 
    
        client.GetStringAsync("http://msdn.microsoft.com");  
    
        // You can do work here that doesn't rely on the string from GetStringAsync.  
        DoIndependentWork();  
    
        // The await operator suspends AccessTheWebAsync.  
        //  - AccessTheWebAsync can't continue until getStringTask is complete.  
        //  - Meanwhile, control returns to the caller of AccessTheWebAsync.  
        //  - Control resumes here when getStringTask is complete.   
        //  - The await operator then retrieves the string result from 
        getStringTask.  
        string urlContents = await getStringTask;  
    
        // The return statement specifies an integer result.  
        // Any methods that are awaiting AccessTheWebenter code hereAsync retrieve the length 
        value.  
        return urlContents.Length;  
    }  
    

提交回复
热议问题