This might be answered somewhere but want to understand the detailed execution for this scenario. Today, I came across MVC action(synchronous) method which is calling an asynchronous method. I don't want this execution to wait synchronously or asynchronously. So, I haven't used the await keyword or wait method. But the outcome has surprised me a lot. Async method got executed some portion and some just skipped the execution. I have reproduced the same scenario and which is also behaving the same. Now, I got the execution but want to understand why this async and method behaving random execution inside the synchronous method. I have pasted the code snippet and output this code.
internal async Task<int> Method1Async()
{
//await Task.Delay(1000);
Console.WriteLine("Inside Method 1 : Before Calling await");
await Task.FromResult(5);
//await Task.Delay(1000);
Console.WriteLine("Inside Method 1 : After Calling await");
return await Task.FromResult(1);
}
internal async Task<int> Method2Async()
{
//await Task.Delay(1000);
Console.WriteLine("Inside Method 2 : Before Calling await");
var res = await Method1Async();
await Task.Delay(1000);
Console.WriteLine("Inside Method 2 : After Calling await");
return res;
}
internal async Task<int> Method3Async()
{
//await Task.Delay(1000);
Console.WriteLine("Inside Method 3 : Before Calling await");
var res = await Method2Async();
await Task.Delay(1000);
Console.WriteLine("Inside Method 3 : After Calling await");
return res;
}
internal void Method4()
{
Method3Async();
}
public static void Main()
{
Console.WriteLine("Inside Main : Before calling Method4");
var demo = new Demo();
demo.Method4();
Console.WriteLine("Inside Main : After calling Method4");
}