How to use async await keywords in any routine

  • Thread starter Thread starter Sudip_inn
  • Start date Start date
S

Sudip_inn

Guest
after reading few article i found we can use await if any function is async by default. i am interested to know how to make any routine using asyn and await ?

see this sample code

static async Task DoSomethingAsync() //A Task return type will eventually yield a void
{
Console.WriteLine("2. Async task has started...");
await GetStringAsync(); // we are awaiting the Async Method GetStringAsync
}

static async Task GetStringAsync()
{
using (var httpClient = new HttpClient())
{
Console.WriteLine("3. Awaiting the result of GetStringAsync of Http Client...");
string result = await httpClient.GetStringAsync(URL); //execution pauses here while awaiting GetStringAsync to complete

//From this line and below, the execution will resume once the above awaitable is done
//using await keyword, it will do the magic of unwrapping the Task<string> into string (result variable)
Console.WriteLine("4. The awaited task has completed. Let's get the content length...");
Console.WriteLine($"5. The length of http Get for {URL}");
Console.WriteLine($"6. {result.Length} character");
}
}

here author can use await because GetStringAsync is async kind of function.

but i want to use await in any function. so how make any routine async await compatible ?

see my below routine where i want to use async & await keyword which allow other to call my sample routine asynchronously.

private List<BrokerData> GetData()
{
List<BrokerData> Bogeylist = Lidistinctdt.AsEnumerable()
.Select(row => new BrokerData
{
Section = (row.Field<string>(0)).ToString(),
LineItem = (row.Field<string>(1)).ToString(),
xFundCode = (row.Field<string>("xFundCode")).ToString()
}).DistinctBy(a => new { a.Section, a.LineItem }).ToList();
}
Now tell me how could i use async & await keyword in my above routine?

please show me. thaks

Continue reading...
 
Back
Top