locked
One of the async method result using another (async) method in .Net - interview question RRS feed

  • Question

  • User423141669 posted

    Can some one help me on the below question in .Net.

    1. One of the async method result using another (async) method, then how to do asynchronously using async and await? if you are waiting for the result it will become synchronous right?

    2. Same question if method one went to infinite loop. so how method2 get to know about it and what will be the output.

    Saturday, December 22, 2018 5:00 PM

All replies

  • User36583972 posted


    Hi XPraxmoxd,

    One of the async method result using another (async) method, then how to do asynchronously using async and await? if you are waiting for the result it will become synchronous right?


    You can refer the following sample:

    // Three things to note in the signature:  
    //  - The method has an async modifier.   
    //  - The return type is Task or Task<T>. (See "Return Types" section.)  
    //    Here, it is Task<int> because the return statement returns an integer.  
    //  - The method name ends in "Async."  
    async Task<int> AccessTheWebAsync()  
    {   
        // You need to add a reference to System.Net.Http to declare client.  
        HttpClient client = new HttpClient();  
      
        // GetStringAsync returns a Task<string>. That means that when you await the  
        // task you'll get a string (urlContents).  
        Task<string> getStringTask = client.GetStringAsync("https://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;  
    }  
    

    For more detailed:
    Asynchronous programming with async and await (C#)

    Same question if method one went to infinite loop. so how method2 get to know about it and what will be the output.

    You can use the IAsyncActionWithProgress<TProgress> Interface or IAsyncOperationWithProgress<TResult, TProgress> Interface to represent an asynchronous operation that can report progress updates to callers.

    Or Cancel a Task and Its Children

    Best Regards,

    Yong Lu

    Monday, December 24, 2018 6:15 AM