Skip to content

Instantly share code, notes, and snippets.

@jessicamilene
Last active November 10, 2021 14:46
Show Gist options
  • Save jessicamilene/00e10cecbb91cdf65c5c30916c4d9a5f to your computer and use it in GitHub Desktop.
Save jessicamilene/00e10cecbb91cdf65c5c30916c4d9a5f to your computer and use it in GitHub Desktop.
[C#] Asynchcronous methods execution examples

Asynchronous Methods - C# Examples

Below we have a synchronous method that counts to 5.

static void Main(string[] args)
{
  Console.WriteLine("START");
  Count();
  Console.WriteLine("END");
  Console.ReadKey();
}

private static void Count()
{
  for (int i = 0; i < 5; i++)
  {
    Console.WriteLine(i + 1);
  }
  Console.WriteLine("End of count");
}

Output

START
1
2
3
4
5
End of count
END

But some times we don't want to stop the code execution to make something, like counting. In the next examples are shown how the code execution is affected by await, async, Task.Run() and .Wait().

Example 1

static void Main(string[] args)
{
  Console.WriteLine("START");
  CountAsync();
  Console.WriteLine("END");
  Console.ReadKey();
}

private static async Task CountAsync()
{
  Task.Run(() => {
    for (int i = 0; i < 5; i++)
    {
      Console.WriteLine(i + 1);
    }
  });
  Console.WriteLine("End of count");
}

Output

START
End of count
END
1
2
3
4
5

Example 2

static void Main(string[] args)
{
  Console.WriteLine("START");
  CountAsync();
  Console.WriteLine("END");
  Console.ReadKey();
}

private static async Task CountAsync()
{
  await Task.Run(() => {
    for (int i = 0; i < 10; i++)
    {
      Console.WriteLine(i + 1);
    }
  });
  Console.WriteLine("End of count");
}

Output

START
END
1
2
3
4
5
End of count

Example 3

static void Main(string[] args)
{
  Console.WriteLine("START");
  CountAsync().Wait();
  Console.WriteLine("END");
  Console.ReadKey();
}

private static async Task CountAsync()
{
  await Task.Run(() => {
    for (int i = 0; i < 10; i++)
    {
      Console.WriteLine(i + 1);
    }
  });
  Console.WriteLine("End of count");
}

Output

START
1
2
3
4
5
End of count
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment