zoukankan      html  css  js  c++  java
  • 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> .

  • 相关阅读:
    SQL 触发器[1]
    SQL 存储过程[1]-常用参数及示例
    前端软件开发体系
    人工智能AI Boosting HMC Memory Chip
    先进一站式IP及定制
    BTC芯片介绍
    ONNX MLIR方法
    MLIR中间表示和编译器框架
    Non-Maximum Suppression,NMS非极大值抑制
    华为计算平台MDC810发布量产
  • 原文地址:https://www.cnblogs.com/lwhkdash/p/6774142.html
Copyright © 2011-2022 走看看