none
How to make any function Async/Await RRS feed

  • Question

  • see a sample function

    public static void Method2()  
        {  
            for (int i = 0; i < 25; i++)  
            {  
                Console.WriteLine(" Method 2");  
            }  
        }  


    tell me how to make this function async await ?

    if function is void too.

    again see the below function 

    static async Task<int> ReadFile(string file)
            {
                int length = 0;
    
                Console.WriteLine(" File reading is stating");
                using (StreamReader reader = new StreamReader(file))
                {
                    // Reads all characters from the current position to the end of the stream asynchronously    
                    // and returns them as one string.    
                    string s = await reader.ReadToEndAsync();
    
                    length = s.Length;
                }
                Console.WriteLine(" File reading is completed");
                return length;
            }  

    await is used with in function but some time we may not be able to see await inside function then how could i make that function async await ? give one example please

    some link i got

    https://www.c-sharpcorner.com/article/async-and-await-in-c-sharp/
    https://visualstudiomagazine.com/blogs/tool-tracker/2018/07/create-async-method.aspx
    https://www.pluralsight.com/guides/understand-control-flow-async-await

    Tuesday, November 5, 2019 8:31 AM

All replies

  • The method implementation shown does not  makes sense to make it async method but you can make it async await like following :

    public static async Task Method2()
    {
        for (int i = 0; i < 25; i++)
        {
            await Task.Factory.StartNew(() => Console.WriteLine(" Method 2"));
        }
    
    }
    But again this can help understanding the syntax and how to use it for method which returns void but the example is not useful any way as the implementation does not needs to be made asynchronous.


    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]


    Blog | LinkedIn | Stack Overflow | Facebook
    profile for Ehsan Sajjad on Stack Exchange, a network of free, community-driven Q&A sites


    Tuesday, November 5, 2019 9:52 AM
  • your code is Ok but if i need to update any winform control from this line await Task.Factory.StartNew(() => Console.WriteLine(" Method 2")); then cross thread operation will occur. so how could i do the same with async / await instead of Task.Factory.StartNew()

    thanks

    Tuesday, November 5, 2019 10:11 AM
  • Here is a model to prevent cross thread violation.

    The following may appear overkill but if you end up doing this over and over again in different projects having this keeps code clean.

    public static class ControlExtensions
    {
        public static void InvokeIfRequired<T>(this T control, Action<T> action) where T : ISynchronizeInvoke
        {
            if (control.InvokeRequired)
            {
                control.Invoke(new Action(() => action(control)), null);
            }
            else
            {
                action(control);
            }
        }
    }

    Usage with a TextBox

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private async void button1_Click(object sender, EventArgs e)
        {
            await ReadStuffTask();
        }
        async Task ReadStuffTask()
        {
            string result;
            using (var reader = File.OpenText("existingfile.txt"))
            {
                result = await reader.ReadToEndAsync();
                textBox1.InvokeIfRequired(textBox => { textBox.Text = result;});
            }
        }
    }


    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, November 5, 2019 10:44 AM
    Moderator