async await task c# code example
Example 1: how to await a task c#
private async void myEvent()
{
Task myTask = MyFunction();
var result = await myTask;
}
private void SomeFunction()
{
myEvent?.Invoke();
Task.WaitAny(myTask);
if(myTask.isCompleted)
DoSomething();
}
Example 2: microsoft asynchronous programming
var allTasks = new List<Task>{eggsTask, baconTask, toastTask};
while (allTasks.Any())
{
Task finished = await Task.WhenAny(allTasks);
if (finished == eggsTask)
{
Console.WriteLine("eggs are ready");
}
else if (finished == baconTask)
{
Console.WriteLine("bacon is ready");
}
else if (finished == toastTask)
{
Console.WriteLine("toast is ready");
}
allTasks.Remove(finished);
}
Juice oj = PourOJ();
Console.WriteLine("oj is ready");
Console.WriteLine("Breakfast is ready!");