BlobService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AllAboutAsyncProgramming.services
{
public class BlobService
{
public async Task<string> GetBlobAsync()
{
Console.WriteLine($"GetBlobAsync - {Environment.CurrentManagedThreadId}");
HttpClient client = new HttpClient();
var result = await client.GetAsync("https://www.google.com");
Console.WriteLine($"GetBlobAsync - {Environment.CurrentManagedThreadId}");
return result.ToString();
}
}
}
Program.cs
using AllAboutAsyncProgramming.services;
class Program
{
public static async Task Main(string[] args)
{
BlobService blobService = new BlobService();
Console.WriteLine($"Main - {Environment.CurrentManagedThreadId}");
var x = await blobService.GetBlobAsync();
Console.WriteLine($"Main - {Environment.CurrentManagedThreadId}");
}
}
Result
example - 1
Main - 1
GetBlobAsync - 1
GetBlobAsync - 6
Main - 6
example - 2 (another run)
Main - 1
GetBlobAsync - 1
GetBlobAsync - 9
Main - 9
Result is always looks like this. first two lines of output get same thread id and bottom two lines of output always get same thread id. (as shown in results section)
When it execute this line of code --> var x = await blobService.GetBlobAsync();
isn't it GetBlobAsync
method should be run on separate thread? But it prints main threads id. after the await
call inside GetBlobAsync
method --> await client.GetAsync("https://www.google.com");
it runs on a separate thread.
I'm confused with the execution flow. How it works? Isn't it should be run on a separate thread when we await something?