Async and Await Query

amanjainits06

Member
Joined
Feb 26, 2022
Messages
5
Programming Experience
3-5
Why the output is like this
123
XYZ
as per my understanding, it should print XYZ first, as I am not writing await in line no. 50


1645898577852.png
 
Ok, you expected what intellisense warn you about line 50, but it looks like that didn't happen, because you're stopping the thread with Thread.Sleep. After that "123" is called before "ABC" in quick succession.
Try changing the sleep to await Task.Delay
 
Last edited:
Im the future, please post your code as text, not as a screenshot.
 
C#:
static void PrintData()
{
    Test1();
    Console.WriteLine("XYZ");
}
static async Task Test1()
{
    await Test();
    Console.WriteLine("123");
}
static async Task Test()
{
    Console.WriteLine("Sleep");
}
Here's a version that works like Thread.Sleep does, what is the output order here?
 
C#:
static void PrintData()
{
    Test1();
    Console.WriteLine("XYZ");
}
static async Task Test1()
{
    await Test();
    Console.WriteLine("123");
}
static async Task Test()
{
    Console.WriteLine("Sleep");
}
Here's a version that works like Thread.Sleep does, what is the output order here?
What editor are you using? ...in visual studio you would have warnings .e.g CS4014 which implies that the processing order is not guaranteed.

What are you trying to achieve; if we knew that; our advice would be far more helpful.
 
What editor are you using? ...in visual studio you would have warnings .e.g CS4014 which implies that the processing order is not guaranteed.

What are you trying to achieve; if we knew that; our advice would be far more helpful.
I think you missed reading this thread from start.
The example is a variation of OP's code, and the processing order is absolutely guaranteed since there is no actual async code taking place. You can't make something async by just putting await on any method call.
 
Why the output is like this
123
XYZ
as per my understanding, it should print XYZ first, as I am not writing await in line no. 50


View attachment 2077
Now in this case also is behaving synchronously
C#:
public async static void PrintData()
        {

            Test1();
            Console.WriteLine("XYZ");
       
            Console.ReadLine();
        }

        public static async Task Test1()
        {
            Console.WriteLine("1");
            await Test2();
            //await Task.Delay(10_000);
            Console.WriteLine("2");
        }

        public static async Task Test2()
        {
            Console.WriteLine("3");
           using (StreamWriter writer = new StreamWriter(@"C:\csc.txt"))
            {
                for (int i = 0; i < 10000000; i++)
                {
                    writer.WriteLine("Monica Rathbun");
                    writer.WriteLine("Vidya Agarwal");
                    writer.WriteLine("Mahesh Chand");
                    writer.WriteLine("Vijay Anand");
                    writer.WriteLine("Jignesh Trivedi");
                }
            }
                Console.WriteLine("4");
        }

        public static void Main(string[] parmeetr)
        {
            PrintData();
        }
 
Last edited by a moderator:
Hi Team ,

My below code is running synchronously and printing 1,3,4 ,2, XYZ .But my understanding is it should print 1, XYZ, 3,4,2 as I have not added await in front of Test1() while calling.
C#:
public async static void PrintData()
        {
            Test1();
            Console.WriteLine("XYZ");      
            Console.ReadLine();
        }

        public static async Task Test1()
        {
            Console.WriteLine("1");
            await Test2();
            Console.WriteLine("2");
        }
        public static async Task Test2()
        {
            Console.WriteLine("3");

            using (StreamWriter writer = new StreamWriter(@"C:\csc.txt"))
            {
                for (int i = 0; i < 10000000; i++)
                {
                    writer.WriteLine("Monica Rathbun");
                    writer.WriteLine("Vidya Agarwal");
                    writer.WriteLine("Mahesh Chand");
                    writer.WriteLine("Vijay Anand");
                    writer.WriteLine("Jignesh Trivedi");
                }

            }
                Console.WriteLine("4");
        }

        public static void Main(string[] parmeetr)
        {
            PrintData();
        }
 

Attachments

  • 1646247048000.png
    1646247048000.png
    44.9 KB · Views: 10
Last edited by a moderator:
And why are you surprised that it is acting synchronously? Where were you expecting the asynchrony to happen?
 
Merged in the other thread that you started since this is still the same topic.
 
@Skydiver
And why are you surprised that it is acting synchronously? Where were you expecting the asynchrony to happen?
Might be my understanding of asynchrony is wrong...i am expecting as that task in method Test2 is time consuming so I don't want to wait for that and let's continue other work..i.e it should print XYZ
Kindly help me to understand async and away.
 
Simply having async on the Test2() method signature on line 14 won't suddenly make the code asynchronous. Neither will simply adding await on the call to Test2() on line 11.

Within Test2() there has to be an opportunity for the current running thread to yield control and return a task back up. The compiler won't magically scan your code within Test2() and decide "ah, this will take a long time. I'm going to insert code in here that will return so that line 11 can await the rest of the code in Test2() to finish executing."

Once again you ignored compiler warning:
Warning CS1998 This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

This illustration and walkthrough in this link may help a little bit in gaining some understanding:

Another thing that may also help is to understand that:
C#:
await DoFooAsync();
DoMoreStuff();
is actually:
C#:
var t = DoFooAsync();
await t;
DoMoreStuff();
or something like:
C#:
var t = DoFooAsync();
t.ContinueWith(() => DoMoreStuff());
Notice that DoFooAsync() needs to return a Task which can be waited on. If DoFooAsync() all synchronous code, it will only return a Task when it gets to the end of the method.
 
@Skydiver Thanks for your response, can you please help me to understand the meeting of "yields control to its caller" I am not understanding this line, also if I want from method Test2() current running thread to yield control and return a task back up how this can be possible?
 
See the link in post #13. Notice in step 6 how control was yielded up to the caller? A similar thing also happened in step 3.
 
Back
Top Bottom