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> .

 

posted on 2017-04-27 16:10  wyman25  阅读(174)  评论(0编辑  收藏  举报

导航