C#Task何时真正开始? [英] When does a C# Task actually start?

查看:615
本文介绍了C#Task何时真正开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任务实际何时开始?

public void DoSomething() {
    Task myTask = DoSomethingAsync();

    Task.WaitAll(new[] { myTask }, 2000);
}

public async Task DoSomethingAsync() {
    await SomethingElse();
}

Task myTask = DoSomethingAsync();中初始化它时会立即启动还是在Task.WaitAll(new[] { myTask }, 2000);中说要等待它时启动?

Does it start immediately when initializing it in Task myTask = DoSomethingAsync(); or does it start when you say to wait for it in Task.WaitAll(new[] { myTask }, 2000); ?

推荐答案

调用async方法将返回 hot 任务,该任务已经启动.因此,没有必要实际代码来强制其运行.

Calling an async method returns a hot task, a task that has already been started. So there is no actual code necessary to force it to run.

根据MSDN(感谢Stephen Cleary )基于任务的异步模式(TAP)模式要求返回的任务很热.这意味着除使用new Task创建的那些任务外,所有其他任务都将很热.

According MSDN (thanks to Stephen Cleary) the Task-based Asynchronous Pattern (TAP) pattern requires returned tasks to be hot. That means that all tasks, except those created with new Task will be hot.

从所引用的文章中:

由公共Task构造函数创建的任务被称为冷任务...所有其他任务在热状态下开始其生命周期.

Tasks that are created by the public Task constructors are referred to as cold tasks... All other tasks begin their life cycle in a hot state.

这篇关于C#Task何时真正开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆