Asynchronous C#\

Threads

- Main thread is typically a User interface thread
- Without async programming, starting a long operation can freeze the main thread.
- With asynchronous programming, the long thread can continue while the main thread is unaffected. 
- `await` - (wait for this to finish and then continue)

worker.cs

class Worker()
{
    public Worker()
    {
        Work();
    }
    public void Work()
    {
        AsyncClass asyncClass = new AsyncClass();
        asyncClass.Work();
        Console.WriteLine("I'm on the Main thread");
        for (int i = 0, i < 10000, i++)
        {
            Console.Write(".");
        }
        Console.WriteLine("Main Thread Completed");
    }

    public class AsyncClass
    {
        public async void Work()
        {
            await SlowTask();
            Console.WriteLine("End Work");
        }
    }
            //   Tasks are preferred on async methods.
    public async Task SlowTask()
    {
        for (int i = o, i < 50, i++)
        {
            Console.WriteLine(i);
            for (int j = 0, j < 10000, j++)
            {
                var k = Math.Sqrt(j);
            }
        }
        Console.WriteLine("Done!")
    }   
}

program.cs

    Worker worker = new Worker();

results matching ""

    No results matching ""