Core C#

Async and the Await Operators

This C# program demonstrates how the await operator is used. The await operator is used with the async specifier to perform simplified multi-threaded programming.

Program.cs

using System;
using System.Threading.Tasks;
using System.Threading;

namespace XoaX {
    class Program {
        async static void DoSomething() {
            // Wait a second
            await Task.Delay(1000);
            Console.WriteLine("The async function is done!");
        }

        static void Main(string[] args) {
            Console.WriteLine("Call the async function:");
            DoSomething();
            Console.WriteLine("This thread doesn't wait.");
            // Wait 2 seconds for the other thread to finish 
            Thread.Sleep(2000);
            Console.WriteLine("The other thread should be done now.");
        }
    }
}
 

Output

Call the async function:
This thread doesn't wait.
The async function is done!
The other thread should be done now.
Press any key to continue . . .
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.