Page 126 - CSharp/C#
P. 126

Chapter 14: Async-Await




        Introduction



        In C#, a method declared async won't block within a synchronous process, in case of you're using
        I/O based operations (e.g. web access, working with files, ...). The result of such async marked
        methods may be awaited via the use of the awaitkeyword.


        Remarks



        An async method can return void, Task or Task<T>.

        The return type Task will wait for the method to finish and the result will be void. Task<T> will return
        a value from type T after the method completes.


        async methods should return Task or Task<T>, as opposed to void, in almost all circumstances. async
        void methods cannot be awaited, which leads to a variety of problems. The only scenario where an
        async should return void is in the case of an event handler.

        async/await works by transforming your async method into a state machine. It does this by creating
        a structure behind the scenes which stores the current state and any context (like local variables),
        and exposes a MoveNext() method to advance states (and run any associated code) whenever an
        awaited awaitable completes.


        Examples



        Simple consecutive calls


         public async Task<JobResult> GetDataFromWebAsync()
         {
           var nextJob = await _database.GetNextJobAsync();
           var response = await _httpClient.GetAsync(nextJob.Uri);
           var pageContents = await response.Content.ReadAsStringAsync();
           return await _database.SaveJobResultAsync(pageContents);
         }


        The main thing to note here is that while every await-ed method is called asynchronously - and for
        the time of that call the control is yielded back to the system - the flow inside the method is linear
        and does not require any special treatment due to asynchrony. If any of the methods called fail,
        the exception will be processed "as expected", which in this case means that the method
        execution will be aborted and the exception will be going up the stack.


        Try/Catch/Finally


        6.0





        https://riptutorial.com/                                                                               72
   121   122   123   124   125   126   127   128   129   130   131