How to call any method asynchronously in c#

后端 未结 5 1694
予麋鹿
予麋鹿 2020-12-07 17:17

Could someone please show me a small snippet of code which demonstrates how to call a method asynchronously in c#?

5条回答
  •  死守一世寂寞
    2020-12-07 18:01

    Check out the MSDN article Asynchronous Programming with Async and Await if you can afford to play with new stuff. It was added to .NET 4.5.

    Example code snippet from the link (which is itself from this MSDN sample code project):

    // Three things to note in the signature: 
    //  - The method has an async modifier.  
    //  - The return type is Task or Task. (See "Return Types" section.)
    //    Here, it is Task because the return statement returns an integer. 
    //  - The method name ends in "Async."
    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 AccessTheWebAsync retrieve the length value. 
        return urlContents.Length;
    }
    

    Quoting:

    If AccessTheWebAsync doesn't have any work that it can do between calling GetStringAsync and awaiting its completion, you can simplify your code by calling and awaiting in the following single statement.

    string urlContents = await client.GetStringAsync();
    

    More details are in the link.

提交回复
热议问题