Task 类的实例(Task.Factory.StartNew 或 TaskCompletionSource)
这可能是一个非常基本的问题,但只是我想确保我头脑中正确的问题。 今天我在挖掘 TPL 库,发现有两种创建 Task 类实例的方法。
方式一
Task<int> t1 = Task.Factory.StartNew(() =>
{
//Some code
return 100;
});
方式二
TaskCompletionSource<int> task = new TaskCompletionSource<int>();
Task t2 = task.Task;
task.SetResult(100);
现在,我只是想知道
- 这些实例之间有什么区别吗?
- 如果是的话怎么办?
This is probably a pretty basic question, but just something that I wanted to make sure I had right in my head.
Today I was digging with TPL library and found that there are two way of creating instance of Task class.
Way I
Task<int> t1 = Task.Factory.StartNew(() =>
{
//Some code
return 100;
});
Way II
TaskCompletionSource<int> task = new TaskCompletionSource<int>();
Task t2 = task.Task;
task.SetResult(100);
Now,I just wanted to know that
- Is there any difference between these instances?
- If yes then what?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您没有在上面的方式 1 中触发任何异步操作,因此您通过消耗线程池中的另一个线程来浪费时间(如果您不更改默认的
TaskScheduler
)。然而,在方式 2 中,您正在生成一个已完成的任务,并在您所在的同一个线程中执行该任务。 TCS 也可以被视为无线程任务(可能是错误的描述,但已被多个开发人员使用)。
As you are not firing any async operation in Way 1 above, you are wasting time by consuming another thread from the threadpool (possibly, if you don't change the default
TaskScheduler
).However, in the Way 2, you are generating a completed task and you do it in the same thread that you are one. TCS can been also seen as a threadless task (probably the wrong description but used by several devs).
第二个示例没有创建“真正的”任务,即没有执行任何操作的委托。
您主要使用它来向调用者呈现任务界面。看一下上面的例子
msdn
The second example does not create a "real" task, i.e. there is no delegate that does anything.
You use it mostly to present a Task interface to the caller. Look at the example on
msdn