One example of await and async from the book
Pro C# 9 with .NET 5: Foundational Principles and Practices in Programming
using System;
using System.Threading;
using System.Threading.Tasks;
namespace AwaitAsyncExample
{
class Program
{
static void Main(string[] args)
{
Task.Run(async () =>
{
await MultipleAwaits();
});
Console.ReadKey();
}
static async Task MultipleAwaits()
{
Task task1 = Task.Run(() =>
{
Thread.Sleep(2_000);
Console.WriteLine("Done with first task!");
});
Task task2 = Task.Run(() =>
{
Thread.Sleep(1_000);
Console.WriteLine("Done with second task!");
});
Task task3 = Task.Run(() =>
{
Thread.Sleep(1_000);
Console.WriteLine("Done with third task!");
});
await Task.WhenAll(task1, task2, task3);
}
}
}
Another example:
private static readonly Object ThisLock = new Object();
static void Main(string[] args)
{
Task.Run(async () =>
{
await MultipleAwaits();
});
Console.ReadKey();
}
static async Task MultipleAwaits()
{
Task task1 = Task.Run(() =>
{
lock (ThisLock)
{
File.AppendAllText("test.txt", "test 1");
}
});
Task task2 = Task.Run(() =>
{
lock (ThisLock)
{
File.AppendAllText("test.txt", "test 2");
}
});
Task task3 = Task.Run(() =>
{
lock (ThisLock)
{
File.AppendAllText("test.txt", "test 3");
}
});
await Task.WhenAll(task1, task2, task3);
}
Notice:
lock (ThisLock)
{
File.AppendAllText("test.txt", "test 2");
}
Without
lock exception "The process cannot access the file 'test.txt' because it is being used by another process." will be raised.
One more example in Windows forms:
namespace AsyncTest;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
btnStart.Click += DoSomeWork;
}
async void DoSomeWork(object sender, EventArgs e)
{
label1.Text = "start";
string text = await DoWait();
label1.Text = text;
}
private Task<string> DoWait()
{
Task<string> task1 = Task.Run(() =>
{
Thread.Sleep(2_000);
return Task.FromResult("did it");
});
return task1;
}
}