Async Await Running Synchronously












1















I'm trying to learn async/await and created the following test code, however it is running synchronously and I'm not sure why.



    class Program
{
static void Main()
{
TestAsync testAsync = new TestAsync();
testAsync.Run();

Console.Read();
}
}

public class TestAsync
{
public async void Run()
{
Task<int> resultTask = GetInt();
Console.WriteLine("2)");
int x = await resultTask;
Console.WriteLine("4)");
}
public async Task<int> GetInt()
{
Task<int> GetIntAfterLongWaitTask = GetIntAfterLongWait();
Console.WriteLine("1)");
int x = await GetIntAfterLongWaitTask;//Expecting execution to go back to Run() since it's not done yet.
Console.WriteLine("3)");
return x;
}

public async Task<int> GetIntAfterLongWait()
{
for (int i = 0; i < 500000000; i++)
{
if (i % 10000000 == 0)
{
Console.WriteLine(i);
}
}

return 23;
}
}


Output is:



<long list of ints>
1)
3)
2)
4)


I expected it to be



<long list of ints>
1)
2)
3)
4)


With 1) being somewhere amongst the long list of ints.



Why is it running synchronously?










share|improve this question























  • GetIntAfterLongWait doesn't have any awaits

    – Mateen Ulhaq
    Nov 22 '18 at 6:45











  • The warning you should be seeing for GetIntAfterLongWait already told you this.

    – Damien_The_Unbeliever
    Nov 22 '18 at 6:45













  • "All" that the async marking on a method does is allow you to write c# code inside that method that includes awaits. By itself, it does nothing else.

    – Damien_The_Unbeliever
    Nov 22 '18 at 6:47











  • I'm not going to VTC as duplicate, but this question covers the ground quite well.

    – Damien_The_Unbeliever
    Nov 22 '18 at 7:51
















1















I'm trying to learn async/await and created the following test code, however it is running synchronously and I'm not sure why.



    class Program
{
static void Main()
{
TestAsync testAsync = new TestAsync();
testAsync.Run();

Console.Read();
}
}

public class TestAsync
{
public async void Run()
{
Task<int> resultTask = GetInt();
Console.WriteLine("2)");
int x = await resultTask;
Console.WriteLine("4)");
}
public async Task<int> GetInt()
{
Task<int> GetIntAfterLongWaitTask = GetIntAfterLongWait();
Console.WriteLine("1)");
int x = await GetIntAfterLongWaitTask;//Expecting execution to go back to Run() since it's not done yet.
Console.WriteLine("3)");
return x;
}

public async Task<int> GetIntAfterLongWait()
{
for (int i = 0; i < 500000000; i++)
{
if (i % 10000000 == 0)
{
Console.WriteLine(i);
}
}

return 23;
}
}


Output is:



<long list of ints>
1)
3)
2)
4)


I expected it to be



<long list of ints>
1)
2)
3)
4)


With 1) being somewhere amongst the long list of ints.



Why is it running synchronously?










share|improve this question























  • GetIntAfterLongWait doesn't have any awaits

    – Mateen Ulhaq
    Nov 22 '18 at 6:45











  • The warning you should be seeing for GetIntAfterLongWait already told you this.

    – Damien_The_Unbeliever
    Nov 22 '18 at 6:45













  • "All" that the async marking on a method does is allow you to write c# code inside that method that includes awaits. By itself, it does nothing else.

    – Damien_The_Unbeliever
    Nov 22 '18 at 6:47











  • I'm not going to VTC as duplicate, but this question covers the ground quite well.

    – Damien_The_Unbeliever
    Nov 22 '18 at 7:51














1












1








1








I'm trying to learn async/await and created the following test code, however it is running synchronously and I'm not sure why.



    class Program
{
static void Main()
{
TestAsync testAsync = new TestAsync();
testAsync.Run();

Console.Read();
}
}

public class TestAsync
{
public async void Run()
{
Task<int> resultTask = GetInt();
Console.WriteLine("2)");
int x = await resultTask;
Console.WriteLine("4)");
}
public async Task<int> GetInt()
{
Task<int> GetIntAfterLongWaitTask = GetIntAfterLongWait();
Console.WriteLine("1)");
int x = await GetIntAfterLongWaitTask;//Expecting execution to go back to Run() since it's not done yet.
Console.WriteLine("3)");
return x;
}

public async Task<int> GetIntAfterLongWait()
{
for (int i = 0; i < 500000000; i++)
{
if (i % 10000000 == 0)
{
Console.WriteLine(i);
}
}

return 23;
}
}


Output is:



<long list of ints>
1)
3)
2)
4)


I expected it to be



<long list of ints>
1)
2)
3)
4)


With 1) being somewhere amongst the long list of ints.



Why is it running synchronously?










share|improve this question














I'm trying to learn async/await and created the following test code, however it is running synchronously and I'm not sure why.



    class Program
{
static void Main()
{
TestAsync testAsync = new TestAsync();
testAsync.Run();

Console.Read();
}
}

public class TestAsync
{
public async void Run()
{
Task<int> resultTask = GetInt();
Console.WriteLine("2)");
int x = await resultTask;
Console.WriteLine("4)");
}
public async Task<int> GetInt()
{
Task<int> GetIntAfterLongWaitTask = GetIntAfterLongWait();
Console.WriteLine("1)");
int x = await GetIntAfterLongWaitTask;//Expecting execution to go back to Run() since it's not done yet.
Console.WriteLine("3)");
return x;
}

public async Task<int> GetIntAfterLongWait()
{
for (int i = 0; i < 500000000; i++)
{
if (i % 10000000 == 0)
{
Console.WriteLine(i);
}
}

return 23;
}
}


Output is:



<long list of ints>
1)
3)
2)
4)


I expected it to be



<long list of ints>
1)
2)
3)
4)


With 1) being somewhere amongst the long list of ints.



Why is it running synchronously?







c# asynchronous async-await






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 '18 at 6:42









Backwards_DaveBackwards_Dave

2,73383368




2,73383368













  • GetIntAfterLongWait doesn't have any awaits

    – Mateen Ulhaq
    Nov 22 '18 at 6:45











  • The warning you should be seeing for GetIntAfterLongWait already told you this.

    – Damien_The_Unbeliever
    Nov 22 '18 at 6:45













  • "All" that the async marking on a method does is allow you to write c# code inside that method that includes awaits. By itself, it does nothing else.

    – Damien_The_Unbeliever
    Nov 22 '18 at 6:47











  • I'm not going to VTC as duplicate, but this question covers the ground quite well.

    – Damien_The_Unbeliever
    Nov 22 '18 at 7:51



















  • GetIntAfterLongWait doesn't have any awaits

    – Mateen Ulhaq
    Nov 22 '18 at 6:45











  • The warning you should be seeing for GetIntAfterLongWait already told you this.

    – Damien_The_Unbeliever
    Nov 22 '18 at 6:45













  • "All" that the async marking on a method does is allow you to write c# code inside that method that includes awaits. By itself, it does nothing else.

    – Damien_The_Unbeliever
    Nov 22 '18 at 6:47











  • I'm not going to VTC as duplicate, but this question covers the ground quite well.

    – Damien_The_Unbeliever
    Nov 22 '18 at 7:51

















GetIntAfterLongWait doesn't have any awaits

– Mateen Ulhaq
Nov 22 '18 at 6:45





GetIntAfterLongWait doesn't have any awaits

– Mateen Ulhaq
Nov 22 '18 at 6:45













The warning you should be seeing for GetIntAfterLongWait already told you this.

– Damien_The_Unbeliever
Nov 22 '18 at 6:45







The warning you should be seeing for GetIntAfterLongWait already told you this.

– Damien_The_Unbeliever
Nov 22 '18 at 6:45















"All" that the async marking on a method does is allow you to write c# code inside that method that includes awaits. By itself, it does nothing else.

– Damien_The_Unbeliever
Nov 22 '18 at 6:47





"All" that the async marking on a method does is allow you to write c# code inside that method that includes awaits. By itself, it does nothing else.

– Damien_The_Unbeliever
Nov 22 '18 at 6:47













I'm not going to VTC as duplicate, but this question covers the ground quite well.

– Damien_The_Unbeliever
Nov 22 '18 at 7:51





I'm not going to VTC as duplicate, but this question covers the ground quite well.

– Damien_The_Unbeliever
Nov 22 '18 at 7:51












1 Answer
1






active

oldest

votes


















3














Confusingly enough, the async keyword will not turn your methods magically asynchronous. Instead, you can consider async methods as a setup for a state machine (see a detailed explanation here), where you schedule the chain of operations by the await calls.



For that reason, your async methods must execute as fast as possible. Do not do any blocking operation in such a setup method. Your GetIntAfterLongWait method is a blocking operation and since it does not contain any awaits the whole content will be executed immediately when the method is called (without any await there is nothing in the method to setup for an async continuation). There must be also a warning about that.



If you have a blocking operation, which you want to execute in the async method, a possible option is to schedule it by an await Task.Run(() => MyLongOperation()); call.



So for example the following example will return immediately because there is nothing to execute before the first await. The return statement will be executed asynchronously as a continuation after the inner awaited task finished:



public async Task<int> GetIntAfterLongWait()
{
await Task.Run(() =>
{
for (int i = 0; i < 500000000; i++)
{
if (i % 10000000 == 0)
{
Console.WriteLine(i);
}
}
});

return 23;
}


For more details see the link above.



Update:



This version will print:



1)
2)
<long list of ints> - but 0 can be before even 1) as Task.Run uses another thread
3)
4)





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53425208%2fasync-await-running-synchronously%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    Confusingly enough, the async keyword will not turn your methods magically asynchronous. Instead, you can consider async methods as a setup for a state machine (see a detailed explanation here), where you schedule the chain of operations by the await calls.



    For that reason, your async methods must execute as fast as possible. Do not do any blocking operation in such a setup method. Your GetIntAfterLongWait method is a blocking operation and since it does not contain any awaits the whole content will be executed immediately when the method is called (without any await there is nothing in the method to setup for an async continuation). There must be also a warning about that.



    If you have a blocking operation, which you want to execute in the async method, a possible option is to schedule it by an await Task.Run(() => MyLongOperation()); call.



    So for example the following example will return immediately because there is nothing to execute before the first await. The return statement will be executed asynchronously as a continuation after the inner awaited task finished:



    public async Task<int> GetIntAfterLongWait()
    {
    await Task.Run(() =>
    {
    for (int i = 0; i < 500000000; i++)
    {
    if (i % 10000000 == 0)
    {
    Console.WriteLine(i);
    }
    }
    });

    return 23;
    }


    For more details see the link above.



    Update:



    This version will print:



    1)
    2)
    <long list of ints> - but 0 can be before even 1) as Task.Run uses another thread
    3)
    4)





    share|improve this answer






























      3














      Confusingly enough, the async keyword will not turn your methods magically asynchronous. Instead, you can consider async methods as a setup for a state machine (see a detailed explanation here), where you schedule the chain of operations by the await calls.



      For that reason, your async methods must execute as fast as possible. Do not do any blocking operation in such a setup method. Your GetIntAfterLongWait method is a blocking operation and since it does not contain any awaits the whole content will be executed immediately when the method is called (without any await there is nothing in the method to setup for an async continuation). There must be also a warning about that.



      If you have a blocking operation, which you want to execute in the async method, a possible option is to schedule it by an await Task.Run(() => MyLongOperation()); call.



      So for example the following example will return immediately because there is nothing to execute before the first await. The return statement will be executed asynchronously as a continuation after the inner awaited task finished:



      public async Task<int> GetIntAfterLongWait()
      {
      await Task.Run(() =>
      {
      for (int i = 0; i < 500000000; i++)
      {
      if (i % 10000000 == 0)
      {
      Console.WriteLine(i);
      }
      }
      });

      return 23;
      }


      For more details see the link above.



      Update:



      This version will print:



      1)
      2)
      <long list of ints> - but 0 can be before even 1) as Task.Run uses another thread
      3)
      4)





      share|improve this answer




























        3












        3








        3







        Confusingly enough, the async keyword will not turn your methods magically asynchronous. Instead, you can consider async methods as a setup for a state machine (see a detailed explanation here), where you schedule the chain of operations by the await calls.



        For that reason, your async methods must execute as fast as possible. Do not do any blocking operation in such a setup method. Your GetIntAfterLongWait method is a blocking operation and since it does not contain any awaits the whole content will be executed immediately when the method is called (without any await there is nothing in the method to setup for an async continuation). There must be also a warning about that.



        If you have a blocking operation, which you want to execute in the async method, a possible option is to schedule it by an await Task.Run(() => MyLongOperation()); call.



        So for example the following example will return immediately because there is nothing to execute before the first await. The return statement will be executed asynchronously as a continuation after the inner awaited task finished:



        public async Task<int> GetIntAfterLongWait()
        {
        await Task.Run(() =>
        {
        for (int i = 0; i < 500000000; i++)
        {
        if (i % 10000000 == 0)
        {
        Console.WriteLine(i);
        }
        }
        });

        return 23;
        }


        For more details see the link above.



        Update:



        This version will print:



        1)
        2)
        <long list of ints> - but 0 can be before even 1) as Task.Run uses another thread
        3)
        4)





        share|improve this answer















        Confusingly enough, the async keyword will not turn your methods magically asynchronous. Instead, you can consider async methods as a setup for a state machine (see a detailed explanation here), where you schedule the chain of operations by the await calls.



        For that reason, your async methods must execute as fast as possible. Do not do any blocking operation in such a setup method. Your GetIntAfterLongWait method is a blocking operation and since it does not contain any awaits the whole content will be executed immediately when the method is called (without any await there is nothing in the method to setup for an async continuation). There must be also a warning about that.



        If you have a blocking operation, which you want to execute in the async method, a possible option is to schedule it by an await Task.Run(() => MyLongOperation()); call.



        So for example the following example will return immediately because there is nothing to execute before the first await. The return statement will be executed asynchronously as a continuation after the inner awaited task finished:



        public async Task<int> GetIntAfterLongWait()
        {
        await Task.Run(() =>
        {
        for (int i = 0; i < 500000000; i++)
        {
        if (i % 10000000 == 0)
        {
        Console.WriteLine(i);
        }
        }
        });

        return 23;
        }


        For more details see the link above.



        Update:



        This version will print:



        1)
        2)
        <long list of ints> - but 0 can be before even 1) as Task.Run uses another thread
        3)
        4)






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 22 '18 at 8:11

























        answered Nov 22 '18 at 7:50









        taffertaffer

        8,23721536




        8,23721536
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53425208%2fasync-await-running-synchronously%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

            Alcedinidae

            RAC Tourist Trophy