Page 119 - CSharp/C#
P. 119

Chapter 13: Async/await, Backgroundworker,


        Task and Thread Examples




        Remarks



        To run any of these examples just call them like that:


         static void Main()
         {
             new Program().ProcessDataAsync();
             Console.ReadLine();
         }


        Examples



        ASP.NET Configure Await


        When ASP.NET handles a request, a thread is assigned from the thread pool and a request
        context is created. The request context contains information about the current request which can
        be accessed through the static HttpContext.Current property. The request context for the request is
        then assigned to the thread handling the request.


        A given request context may only be active on one thread at a time.

        When execution reaches await, the thread handling a request is returned to the thread pool while
        the asynchronous method runs and the request context is free for another thread to use.


         public async Task<ActionResult> Index()
         {
             // Execution on the initially assigned thread
             var products = await dbContext.Products.ToListAsync();

             // Execution resumes on a "random" thread from the pool
             // Execution continues using the original request context.
             return View(products);
         }


        When the task completes the thread pool assigns another thread to continue execution of the
        request. The request context is then assigned to this thread. This may or may not be the original
        thread.


        Blocking


        When the result of an async method call is waited for synchronously deadlocks can arise. For
        example the following code will result in a deadlock when IndexSync() is called:






        https://riptutorial.com/                                                                               65
   114   115   116   117   118   119   120   121   122   123   124