Resolved Nothing happen , when async method runs

Dragon4ik

Member
Joined
Oct 24, 2020
Messages
16
Programming Experience
Beginner
I'm bad in async programming, so tried to make a simple program, which should consolidate my knowledge. But when I compile code, nothing happen
Here is my code:
C#:
static void Main(string[] args)
        {
           

            int x,y;

            x = y = 0;

            string str = "abcd";

            ASyncGet(x,y,str);
        }

static async void ASyncGet(int i1,int i2, string str)
        {
            Task t1 = Task.Run(()=>Get1(str));
            Task t2 = Task.Run(() => Get2(str));

            await Task.WhenAll(t1, t2);

         
        }

        static int Get(string str)
        {
            int i = 0;

            for (int j = 0; j < str.Length; j++)
            {
                i++;
                Console.WriteLine(str[j]);
            }

            return i;
        }

        static async Task<int> Get1(string str)
        {
            return await Task.Run(() =>Get(str));
        }

        static async Task<int> Get2(string str)
        {
            return await Task.Run(() => Get(str));
        }

I tried debugging, but process stops on this line:
C#:
 await Task.WhenAll(t1, t2);

Please, can you help and explain , what I do wrongly?
P.S. Thank you in advance
 
Last edited:
Solution
You should NEVER declare a method async void unless it is an event handler. Otherwise, a method that would be declared void if synchronous should be declared async Task. If you declare your ASyncGet method that way then you can actually wait for it to complete. As it stands, you call that method and, because it is asynchronous, it returns immediately and then your application quits. You need to await that task to see the results of what it does.
You should NEVER declare a method async void unless it is an event handler. Otherwise, a method that would be declared void if synchronous should be declared async Task. If you declare your ASyncGet method that way then you can actually wait for it to complete. As it stands, you call that method and, because it is asynchronous, it returns immediately and then your application quits. You need to await that task to see the results of what it does.
 
Solution
I just tested your code and, even as it is, it still works if you add a Console.ReadLine call at the end of the Main method. You don't get to see the console output because the application quits too quickly. With that call there the app will wait for you to close it and you will see the output. That's pretty much the same as any synchronous console app.
 
Back
Top Bottom