none
How to use async await keywords in any routine RRS feed

  • Question


  • 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
    Tuesday, December 17, 2019 12:49 PM

Answers

  • I have done this job this way

    private async void button1_Click(object sender, EventArgs e)
    {
    	DataTable dt = new DataTable();
    	dt.Columns.Add("Section", typeof(string));
    	dt.Columns.Add("LineItem", typeof(string));
    	DataRow dr = dt.NewRow();
    	dr["Section"] = "Test1";
    	dr["LineItem"] = "Test2";
    	dt.Rows.Add(dr);
    
    	var task1 = GetData(dt);
    	await Task.WhenAll(task1);
    
    	List<BrokerData> _tmp = task1.Result;
    }
    
    private async Task<List<BrokerData>> GetData(DataTable Lidistinctdt)
    {
    	List<BrokerData> Bogeylist = null;
    
    	await Task.Run(() =>
    	{
    		Bogeylist = Lidistinctdt.AsEnumerable()
    	   .Select(row => new BrokerData
    	   {
    		   Section = (row.Field<string>(0)).ToString(),
    		   LineItem = (row.Field<string>(1)).ToString()
    
    	   }).ToList();
    	});
    
    	return Bogeylist;
    } 
    
    public class BrokerData
    {
    	public string Section { get; set; }
    
    	public string LineItem { get; set; }
    }		
    i have to use await Task.Run() to make the routine async. tell me how to make my routine async awaitable without using Task.Run()

    • Marked as answer by Sudip_inn Wednesday, December 18, 2019 10:37 AM
    Tuesday, December 17, 2019 1:10 PM
  • Here is a working example which returns Task<List<T>>

    No DataTable used, instead data is read asynchronously using a DataReader.  One field is async, the other not to show the difference.

    Full source is here

    https://github.com/karenpayneoregon/DataGridViewButtonAsync


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by Sudip_inn Wednesday, December 18, 2019 10:38 AM
    Tuesday, December 17, 2019 3:15 PM
    Moderator

All replies

  • I have done this job this way

    private async void button1_Click(object sender, EventArgs e)
    {
    	DataTable dt = new DataTable();
    	dt.Columns.Add("Section", typeof(string));
    	dt.Columns.Add("LineItem", typeof(string));
    	DataRow dr = dt.NewRow();
    	dr["Section"] = "Test1";
    	dr["LineItem"] = "Test2";
    	dt.Rows.Add(dr);
    
    	var task1 = GetData(dt);
    	await Task.WhenAll(task1);
    
    	List<BrokerData> _tmp = task1.Result;
    }
    
    private async Task<List<BrokerData>> GetData(DataTable Lidistinctdt)
    {
    	List<BrokerData> Bogeylist = null;
    
    	await Task.Run(() =>
    	{
    		Bogeylist = Lidistinctdt.AsEnumerable()
    	   .Select(row => new BrokerData
    	   {
    		   Section = (row.Field<string>(0)).ToString(),
    		   LineItem = (row.Field<string>(1)).ToString()
    
    	   }).ToList();
    	});
    
    	return Bogeylist;
    } 
    
    public class BrokerData
    {
    	public string Section { get; set; }
    
    	public string LineItem { get; set; }
    }		
    i have to use await Task.Run() to make the routine async. tell me how to make my routine async awaitable without using Task.Run()

    • Marked as answer by Sudip_inn Wednesday, December 18, 2019 10:37 AM
    Tuesday, December 17, 2019 1:10 PM
  • Use

    var task1 = await GetData(dt); and .ConfigureAwait(false); off the Task.

    See and read so you have an understanding of what is going on.

    https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html  

    Then read

    https://stackoverflow.com/questions/23854102/using-async-await-with-datareader-without-middle-buffers


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Tuesday, December 17, 2019 1:30 PM
    Moderator
  • Here is a working example which returns Task<List<T>>

    No DataTable used, instead data is read asynchronously using a DataReader.  One field is async, the other not to show the difference.

    Full source is here

    https://github.com/karenpayneoregon/DataGridViewButtonAsync


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by Sudip_inn Wednesday, December 18, 2019 10:38 AM
    Tuesday, December 17, 2019 3:15 PM
    Moderator
  • you said ConfigureAwait(false); off the Task

    what ConfigureAwait does ?

    i am looking for a trick how could i use async await in any function without using Task.Run(). if you know then please share the idea. thanks

    Wednesday, December 18, 2019 10:40 AM