multithreading in regards toTask, async, and await

I have the following code and just want to make sure I have the concept of multithreading down on a high level.

public async Task<List<Category>> GetProjectsByCategoryIDAsync(Int16 categoryid)
    {
        try
        {
            using (YeagerTechEntities DbContext = new YeagerTechEntities())
            {
                DbContext.Configuration.ProxyCreationEnabled = false;
                DbContext.Database.Connection.Open();

                var category = await DbContext.Categories.Include("Projects").Where(p => p.CategoryID == categoryid).ToListAsync();

                return category;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

It is my understanding of the following:

  • async - declares a method to run asynchounously instead of synchrounously.
  • Task - declares a method to run as a task on a single thread
  • await - the task waits for the operation to complete.
  • Where I am a little fuzzy about is the await keyword. Obviously, the benefit of asynchrounous programming is that the method supposedly doesn't have to wait for the task to complete before another request comes in right behind it. But with the await keyword, the task waits until the operation is finished.

    With synchrounous programming, everything is processed in a sequential pattern.

    How does this methodology allow for requests to come in simultaneously and be executed in a much faster fashion than synchronous programming??

    I just need a high level explanation to get the concept down.

    Thanks so much in advance.


    Consider the following code:

        public async Task DoSomething()
        {
            Console.WriteLine("Begin");
            int i = await DoSomethingElse();
            Console.WriteLine("End " + i);
        }
    
        public Task<int> DoSomethingElse()
        {
            return new Task<int>(() =>
            {
                // do heavy work
                Thread.Sleep(1000);
                return 1;
            });
    
        }
    

    With synchrounous programming, everything is processed in a sequential pattern.

    The code above is asynchronous, but is still sequential. The difference between that code and its synchronous version (eg, public int DoSomethingElse ) is that when you await DoSomethingElse , the main thread will be freed to do other work, instead of blocking waiting for DoSomethingElse to complete.

    What actually happens is: your async DoSomething method will run on thread A and be broken in two.

  • the first part will print "Begin" and make an async call, and then return .
  • the second part will print "End"
  • After the first part of the method executes, Thread A will be free to do other work. Meanwhile, Thread B will be executing the lambda expression that does some heavy work. Whenever Thread B completes, the second part of your method will be scheduled to run on Thread A, and "End" will be printed.

    Notice that, while Thread B was executing the heavy work, Thread A was free to do other stuff.

    How does this methodology allow for requests to come in simultaneously and be executed in a much faster fashion than synchronous programming??

    In frameworks such as ASP.NET MVC, your application has a finite number of threads available to handle incoming requests (lets call these "request threads"). By delegating heavy work to other threads and awaiting, your request threads will be free to handle more incoming requests while heavy work is being done.

    This diagram, although complex, illustrates the execution/suspension flow of threads executing asynchronous work:

    在这里输入图像描述

    Notice how at step 6 the thread was yielded, and then step 7 resumed the execution of the method. As you can see, the await keyword effectively breaks the method in two.

    链接地址: http://www.djcxy.com/p/79316.html

    上一篇: 等待一个空的Task永久旋转(等待新任务(()=> {}))

    下一篇: 关于任务,异步和等待的多线程