了解在一行中使用Task.Run + Wait()+ async + await的用法 [英] Understanding the use of Task.Run + Wait() + async + await used in one line

查看:627
本文介绍了了解在一行中使用Task.Run + Wait()+ async + await的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#新手,所以我很难理解一些概念,并且遇到了一段我不太了解的代码:

I'm a C# newbie, so I'm struggling to understand some concepts, and I run into a piece of code that I'm not quite understanding:

static void Main(string[] args)
{
 Task.Run(async () => { await SomeClass.Initiate(new Configuration()); }).Wait();
 while (true) ;
}

据我了解,这会运行一个启动方法的任务.该方法开始运行,一旦完成,便进入无限循环等待.感觉是代码没有意义,或者我理解不正确.

As I understand, this runs a task which initiates a method. This method runs, and then, once it finished, it gets into an infinite loop waiting. It feels that either the code doesn't make sense, or that I'm not understanding right.

谢谢

推荐答案

您可以将其分为几个部分:

You can break this apart into several parts:

async () => { await SomeClass.Initiate(new Configuration()); }

是一个lambda表达式,它定义一个等待另一个方法的async方法.然后将此lambda传递给Task.Run:

Is a lambda expression that defines an async method that just awaits another method. This lambda is then passed to Task.Run:

Task.Run(async () => { await SomeClass.Initiate(new Configuration()); })

Task.Run在线程池线程上执行其代码.因此,该async lambda将在线程池线程上运行. Task.Run返回一个Task,它表示async lambda的执行.调用Task.Run之后,代码将调用Task.Wait:

Task.Run executes its code on a thread pool thread. So, that async lambda will be run on a thread pool thread. Task.Run returns a Task which represents the execution of the async lambda. After calling Task.Run, the code calls Task.Wait:

Task.Run(async () => { await SomeClass.Initiate(new Configuration()); }).Wait();

这将阻止主控制台应用程序,直到异步lambda完全完成.

This will block the main console app until the async lambda is completely finished.

如果您想进一步了解它,以下内容大致相同:

If you want to see how it's broken out further, the following is roughly equivalent:

static async Task AnonymousMethodAsync()
{
  await SomeClass.Initiate(new Configuration());
}

static void Main(string[] args)
{
  var task = Task.Run(() => AnonymousMethodAsync());
  task.Wait();
  while (true) ;
}

这篇关于了解在一行中使用Task.Run + Wait()+ async + await的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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