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

 

转载于:https://www.cnblogs.com/lwhkdash/p/6774142.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值