locked
await call locks UI thread, non responsive

    Question

  • Hi everyone,

    I have the following code:

     

     private async void btnStart_Click(object sender, RoutedEventArgs e)
    
      {  
    
       Task<string> x = await TaskEx.Run(() => GetA());
    
       txtResults.Text = x.Result;
    
    
    
      }
    
    
    
      private async Task<string> GetA()
    
      {
    
       return await new Task<string>(() => "t");
    
      }
    
    

    for some reason, the x.Result never returns anything. Can anyone tell me what im doing wrong here? I am completely stuck at the moment.

    [edit] forgot to add! this then makes my UI completely non responsive!

    Thanks in advance!
    Cheers,

    Adam

    

    

     

     

     

     

     

     

     

     

    


    Monday, June 6, 2011 11:57 AM

Answers

  • The problem is your GetA method - instead of using Task.Run(), you're just creating a new Task.  However, you never actually Start() the Task you create.  As such, it never runs, so the process never completes.

     

    You can fix this quite a few ways.  One option would be just to directly return the task from Task.Run, like so:

    private Task<string> GetA()
    {
      return Task.Run(() => "t");
    }
    
    


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    • Marked as answer by AdamG85 Monday, June 6, 2011 11:51 PM
    Monday, June 6, 2011 4:11 PM
    Moderator

All replies

  • The problem is your GetA method - instead of using Task.Run(), you're just creating a new Task.  However, you never actually Start() the Task you create.  As such, it never runs, so the process never completes.

     

    You can fix this quite a few ways.  One option would be just to directly return the task from Task.Run, like so:

    private Task<string> GetA()
    {
      return Task.Run(() => "t");
    }
    
    


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    • Marked as answer by AdamG85 Monday, June 6, 2011 11:51 PM
    Monday, June 6, 2011 4:11 PM
    Moderator
  • im not at home to actually test this out, but that makes perfect sense!!!!!! thankyou so much reed, i was banging my head against a brick wall trying to figure this out. so damn simple!


    Cheers,

    Adam

    Monday, June 6, 2011 11:52 PM