Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. async and await concept

async and await concept

Scheduled Pinned Locked Moved C#
question
8 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Anil Sharma1983
    wrote on last edited by
    #1

    i am trying to understand async and await concept. so i am make sample program when i run this program take 8 seconds to execute if i execute without async and await it also take 8 second to execute. so what is wrong in this program.

    protected async void btnSubmit_Click(object sender, EventArgs e)
    {

       Response.Write(DateTime.Now.ToString("dd-MM-yyyy:hh:mm:ss") + " <br/>");
    
       //dowork();
       await Task.Run(() => dowork());
      // await Task.Run(() => DoAnotherWork());
    
       DoAnotherWork();
       Response.Write(DateTime.Now.ToString("dd-MM-yyyy:hh:mm:ss") + " <br/>");
       // btnSubmit.Text="Done it";
    

    }

    void dowork()
    {
    Thread.Sleep(5000);
    }
    void DoAnotherWork()
    {
    Thread.Sleep(3000);

    }

    P F Richard DeemingR 3 Replies Last reply
    0
    • A Anil Sharma1983

      i am trying to understand async and await concept. so i am make sample program when i run this program take 8 seconds to execute if i execute without async and await it also take 8 second to execute. so what is wrong in this program.

      protected async void btnSubmit_Click(object sender, EventArgs e)
      {

         Response.Write(DateTime.Now.ToString("dd-MM-yyyy:hh:mm:ss") + " <br/>");
      
         //dowork();
         await Task.Run(() => dowork());
        // await Task.Run(() => DoAnotherWork());
      
         DoAnotherWork();
         Response.Write(DateTime.Now.ToString("dd-MM-yyyy:hh:mm:ss") + " <br/>");
         // btnSubmit.Text="Done it";
      

      }

      void dowork()
      {
      Thread.Sleep(5000);
      }
      void DoAnotherWork()
      {
      Thread.Sleep(3000);

      }

      P Offline
      P Offline
      Pete OHanlon
      wrote on last edited by
      #2

      How long would you expect it to complete in? You have 8 seconds worth of operation in there. I assume that you think that dowork will happen at the same time as DoAnotherWork. That's not the way that await operates. It's not, despite what you may think, something that pushes an operation off to another thread and continues processing in that thread - instead, it suspends the operation of the current method until the awaited operation completes. So, you end up with an 8 second delay.

      A 1 Reply Last reply
      0
      • P Pete OHanlon

        How long would you expect it to complete in? You have 8 seconds worth of operation in there. I assume that you think that dowork will happen at the same time as DoAnotherWork. That's not the way that await operates. It's not, despite what you may think, something that pushes an operation off to another thread and continues processing in that thread - instead, it suspends the operation of the current method until the awaited operation completes. So, you end up with an 8 second delay.

        A Offline
        A Offline
        Anil Sharma1983
        wrote on last edited by
        #3

        yes, i was thinking it should completed in 5 seconds. So please clarify to me await and async concept. thanks your help

        P A 2 Replies Last reply
        0
        • A Anil Sharma1983

          yes, i was thinking it should completed in 5 seconds. So please clarify to me await and async concept. thanks your help

          P Offline
          P Offline
          Pete OHanlon
          wrote on last edited by
          #4

          I just have clarified it for you. The await keyword suspends the method until the task it's waiting on completes, then it moves onto the next operation in the chain. I'm not sure how else I can put this for you.

          A 1 Reply Last reply
          0
          • P Pete OHanlon

            I just have clarified it for you. The await keyword suspends the method until the task it's waiting on completes, then it moves onto the next operation in the chain. I'm not sure how else I can put this for you.

            A Offline
            A Offline
            Anil Sharma1983
            wrote on last edited by
            #5

            thanks Peter for your help

            1 Reply Last reply
            0
            • A Anil Sharma1983

              yes, i was thinking it should completed in 5 seconds. So please clarify to me await and async concept. thanks your help

              A Offline
              A Offline
              Agent__007
              wrote on last edited by
              #6

              Anil0007 wrote:

              i was thinking it should completed in 5 seconds

              Well, if you modify your code something like this, it "might" run in 5 seconds..

              	 Task t0 = Task.Factory.StartNew(() => dowork());
              	 Task t1 = Task.Factory.StartNew(() => DoAnotherWork());
              	 
              	 await Task.WhenAll(t0, t1);
              

              You have just been Sharapova'd.

              1 Reply Last reply
              0
              • A Anil Sharma1983

                i am trying to understand async and await concept. so i am make sample program when i run this program take 8 seconds to execute if i execute without async and await it also take 8 second to execute. so what is wrong in this program.

                protected async void btnSubmit_Click(object sender, EventArgs e)
                {

                   Response.Write(DateTime.Now.ToString("dd-MM-yyyy:hh:mm:ss") + " <br/>");
                
                   //dowork();
                   await Task.Run(() => dowork());
                  // await Task.Run(() => DoAnotherWork());
                
                   DoAnotherWork();
                   Response.Write(DateTime.Now.ToString("dd-MM-yyyy:hh:mm:ss") + " <br/>");
                   // btnSubmit.Text="Done it";
                

                }

                void dowork()
                {
                Thread.Sleep(5000);
                }
                void DoAnotherWork()
                {
                Thread.Sleep(3000);

                }

                F Offline
                F Offline
                F ES Sitecore
                wrote on last edited by
                #7

                Using await doesn't mean your code acts asynchronously. It still behaves as if the code is running synchronously (which is why it takes 8 seconds) but the difference is that when using await the underlying framework means the thread is available to use for other tasks if needed. If you didn't use await and instead just waited for the task to finish then your code would act no differently, but the thread that is waiting for the result can't be used for something else if needed. If you remove the "await" from the dowork then the method will take 3 seconds as dowork will be started on its own task and that will execute asynchronously and then DoAnotherWork will be called which will block for 3s synchronously.

                dowork(); // this will block execution for 5s as dowork is executed on the current thread
                Task.Run(() => dowork()); // the dowork will happen on its own thread and that thread will run for 5 seconds
                // but the code in this block will continue to run so dowork is an asynchronous call
                await Task.Run(() => dowork()); // a mix of both the above. The task will still run on its own thread for
                // 5 seconds, but execution will wait until that new thread has finished

                1 Reply Last reply
                0
                • A Anil Sharma1983

                  i am trying to understand async and await concept. so i am make sample program when i run this program take 8 seconds to execute if i execute without async and await it also take 8 second to execute. so what is wrong in this program.

                  protected async void btnSubmit_Click(object sender, EventArgs e)
                  {

                     Response.Write(DateTime.Now.ToString("dd-MM-yyyy:hh:mm:ss") + " <br/>");
                  
                     //dowork();
                     await Task.Run(() => dowork());
                    // await Task.Run(() => DoAnotherWork());
                  
                     DoAnotherWork();
                     Response.Write(DateTime.Now.ToString("dd-MM-yyyy:hh:mm:ss") + " <br/>");
                     // btnSubmit.Text="Done it";
                  

                  }

                  void dowork()
                  {
                  Thread.Sleep(5000);
                  }
                  void DoAnotherWork()
                  {
                  Thread.Sleep(3000);

                  }

                  Richard DeemingR Offline
                  Richard DeemingR Offline
                  Richard Deeming
                  wrote on last edited by
                  #8

                  It's not usually recommended to use Task.Run to convert a synchronous method to an async Task, especially if you're going to immediately await that Task: Should I expose asynchronous wrappers for synchronous methods? | Stephen Toub[^] Instead, it's better to push the asynchronous operation down, and make the method your calling return a Task. Also, when you're using async, you should try to avoid Thread.Sleep; use await Task.Delay(...) instead: Visual C#: Thread.Sleep vs. Task.Delay[^] And as Agent__007 said, if you want both methods to run in parallel, you need to use Task.WhenAll to wait for them.

                  protected async void btnSubmit_Click(object sender, EventArgs e)
                  {
                  Response.Write(DateTime.Now.ToString("dd-MM-yyyy:hh:mm:ss") + " <br/>");

                  Task first = dowork();
                  Task second = DoAnotherWork();
                  await Task.WhenAll(first, second);
                  
                  Response.Write(DateTime.Now.ToString("dd-MM-yyyy:hh:mm:ss") + " <br/>");
                  

                  }

                  async Task dowork()
                  {
                  await Task.Delay(5000);
                  }

                  async Task DoAnotherWork()
                  {
                  await Task.Delay(3000);
                  }

                  Since you're using ASP.NET WebForms, you should consider using the RegisterAsyncTask method[^] to run your async code, and avoid using async void where possible: Using Asynchronous Methods in ASP.NET 4.5[^]

                  "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups