In this asynchronous method, there are no “wait” statements and will be executed synchronously

my program has 3 warnings of the following statement:

In this asynchronous method, there are no “wait” statements and will be executed synchronously. Think of it using the “wait” operator to wait for non-blocking API calls, or “wait for Task.Run (...)” to do the work of binding to the processor in the background thread.

What warning is trying to tell me? What should I do?

This is my code: does it work with multithreading?

static void Main(string[] args)
{
    Task task1 = new Task(Work1);
    Task task2 = new Task(Work2);
    Task task3 = new Task(Work3);

    task1.Start();
    task2.Start();
    task3.Start();

    Console.ReadKey();
}

static async void Work1()
{
    Console.WriteLine("10 started");
    Thread.Sleep(10000);
    Console.WriteLine("10 completed");
}

static async void Work2()
{
    Console.WriteLine("3 started");
    Thread.Sleep(3000);
    Console.WriteLine("3 completed");
}

static async void Work3()
{
    Console.WriteLine("5 started");
    Thread.Sleep(5000);
    Console.WriteLine("5 completed");
}
+4
source share
4 answers

async, , . , .

async?

  • , , await
  • , await, .
  • , , Task.

, a) await b) void, . - async - await . await .

+3

(Work1, Work2, Work3) async, await .

0

, , , . , , async. , , .

async/await, Task.Delay(), async/await :

static async void Work3()
{
    Console.WriteLine("5 started");
    await Task.Delay(5000);
    Console.WriteLine("5 completed");
}
0

You used the keyword ' async', which indicates that the methods Work1 (), Work2 () and Work3 () are executed asynchronously, but you have not used the keyword 'wait'. So it runs as synchronously. Use ' await' if you want to execute it asynchronously.

 static async void Work1()
 {
     Console.WriteLine("10 started");
    await Task.Delay(10000);
     Console.WriteLine("10 completed");
 }

 static async void Work2()
 {
     Console.WriteLine("3 started");
     await Task.Delay(3000);
     Console.WriteLine("3 completed");
 }

 static async void Work3()
 {
     Console.WriteLine("5 started");
     await Task.Delay(5000);
     Console.WriteLine("5 completed");
 }
0
source

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


All Articles