Understanding the use of Task.Run + Wait () + async + wait is used on one line

I'm new to C #, so I'm trying to understand some concepts, and I come across a piece of code that I don't quite understand:

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

As I understand it, this launches a task that initiates a method. This method starts, and then, as soon as it finishes, it goes into an infinite wait loop. He feels that either the code does not make sense, or that I do not understand correctly.

thank

+4
source share
3 answers

You can break it down into several parts:

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

It is a lambda expression that defines a method asyncthat just expects another method. Then this lambda is passed to Task.Run:

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

Task.Run . , async lambda . Task.Run a Task, async . Task.Run Task.Wait:

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

, .

, , :

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

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

.NET Fiddle, Console.WriteLine, , , .

Task.Run Task, (, ). Func<Task>. async await, SomeClass.Initiate - .

, .

, , , .

Task, Task.Run, .Wait().

.

Task.Run , .Wait() Task, SomeClass.Initiate.

, - Console.ReadLine , Enter.

+2

, SomeClass.Initiate - , async . - Task.Run, . - .Wait(), .

while (true) ; , VS , , - Console.ReadLine(). while(true) async- , .Wait() .

, async .Wait() .Result - while(true) .

See async in a console application in C #? to run asynchronous code correctly in a console application (simple .Wait()or .Result)

+1
source

Source: https://habr.com/ru/post/1655370/


All Articles