不使用 Task.Run 或 TaskFactory.StartNew 开始任务
Start a task without the use of Task.Run or TaskFactory.StartNew
让我们看看:
Task.Run
Method (Action): Queues the specified work to run on the ThreadPool and returns a task handle for that work.
和
TaskFactory.StartNew
Method (Action): Creates and starts a task.
但我的代码中没有它们。它仍然可以启动并且运行。为什么?
static void Main(string[] args)
{
Task t = AsynchronyWithTPL();
t.Wait();
}
static Task AsynchronyWithTPL()
{
Task<string> t = GetInfoAsync("Task 1");
Task t2 = t.ContinueWith(task => Console.WriteLine(t.Result), TaskContinuationOptions.NotOnFaulted);
Task t3 = t.ContinueWith(task => Console.WriteLine(t.Exception.InnerException), TaskContinuationOptions.NotOnFaulted);
return Task.WhenAny(t2, t3);
}
似乎Task.Wait
方法启动了任务,但这是一个好的做法吗?
首先。 Task.Wait
不启动任务,它等待任务完成。
您可以使用 Task.Run
、Task.Factory.StartNew
、new Task(...).Start()
或调用 async
任务(我假设 GetInfoAsync
是).
一个 async
方法 returns 在该方法调用返回之前启动的 "hot" 任务。在您的情况下,您向该任务添加延续 (t2
、t3
),然后使用 Task.WhenAny
.
在两者之上创建延续
如果您正在处理 async
任务,则无需启动这些任务(您也没有)。如果您想将工作卸载到 ThreadPool
,请使用 Task.Run
。不要使用 Task.Factory.StartNew
或 new Task(...).Start()
除非你必须(这应该是非常罕见的)。
我猜(我可能是错的)你想写的是这样的:
static async Task AsynchronyWithTPL()
{
try
{
Console.WriteLine(await GetInfoAsync("Task 1"));
}
catch (AggregateException exception)
{
Console.WriteLine(exception.InnerException);
}
}
让我们看看:
Task.Run
Method (Action): Queues the specified work to run on the ThreadPool and returns a task handle for that work.
和
TaskFactory.StartNew
Method (Action): Creates and starts a task.
但我的代码中没有它们。它仍然可以启动并且运行。为什么?
static void Main(string[] args)
{
Task t = AsynchronyWithTPL();
t.Wait();
}
static Task AsynchronyWithTPL()
{
Task<string> t = GetInfoAsync("Task 1");
Task t2 = t.ContinueWith(task => Console.WriteLine(t.Result), TaskContinuationOptions.NotOnFaulted);
Task t3 = t.ContinueWith(task => Console.WriteLine(t.Exception.InnerException), TaskContinuationOptions.NotOnFaulted);
return Task.WhenAny(t2, t3);
}
似乎Task.Wait
方法启动了任务,但这是一个好的做法吗?
首先。 Task.Wait
不启动任务,它等待任务完成。
您可以使用 Task.Run
、Task.Factory.StartNew
、new Task(...).Start()
或调用 async
任务(我假设 GetInfoAsync
是).
一个 async
方法 returns 在该方法调用返回之前启动的 "hot" 任务。在您的情况下,您向该任务添加延续 (t2
、t3
),然后使用 Task.WhenAny
.
如果您正在处理 async
任务,则无需启动这些任务(您也没有)。如果您想将工作卸载到 ThreadPool
,请使用 Task.Run
。不要使用 Task.Factory.StartNew
或 new Task(...).Start()
除非你必须(这应该是非常罕见的)。
我猜(我可能是错的)你想写的是这样的:
static async Task AsynchronyWithTPL()
{
try
{
Console.WriteLine(await GetInfoAsync("Task 1"));
}
catch (AggregateException exception)
{
Console.WriteLine(exception.InnerException);
}
}