• Thread in depth 2:Asynchronization and Task


    When we want to do a work asynchronously, creating a new thread is a good way. .NET provides two others ways rather than create thread explicitly, that is ThreadPool and Task.

    ThreadPool

    Every single CLR maintains a threadpool.There is a queue for user action request inside the threadpool.Everytime an action entry is queued by calling the ThreadPool.QueueUserWorkItem method, threadpool will pick up or create a thread to do the work.When the work is done,the thread will be returned to threadpool rather than be destroyed.

    Task

    ThreadPool is deficient that you can hardly know when is the work done and hardly get the returning result. In this case, Task may be a better answear.

    1. You can do a work asynchronously by calling Task.Run() method or the start() method of a instance of Task.
    2. Invoke the Wait() method to block the caller thread and wait until the task is done, meanwhile, access to the Result property of a task instance will block the caller thread, because it will call wait() method inside the Result property.
    3. Task supports cancellation just as ThreadPool do, by using the CancellationTokenSource.
    4. Can arrange one or more continuous works to be executed as soon as the task is done, by invoking the ContinueWith() method.But note that the continuous works may not be executed in the same thread of the origin work.

    async and await

    When access to the Result property to get the returning result of a task, the caller thread will be blocked to wait for the task get done. In this case, you can use the "await" keyword to let the control return to the caller thread while waitting for the result of the task.

    If await is used inside a method, then the async modifier is required on the method, and, if a method is decorated by async, the return type of this method should only be void or Task or Task<TResult> .

  • 相关阅读:
    IE, FireFox, Opera 浏览器支持CSS实现Alpha半透明的方法
    5个CSS3技术实现设计增强
    SQL Server 2005 中的分区表和索引
    推荐12款可用于前端开发的免费文本编辑器
    960 Grid System
    初识Byte
    在线制作网站
    sqlserver操作符篇 优化
    ASP.NET 异常处理
    Photoshop 隐藏的快捷键
  • 原文地址:https://www.cnblogs.com/lwhkdash/p/6774142.html
Copyright © 2020-2023  润新知