-1

I am following this to get async/await working.

But when I run the below code as debug , it only prints

HandleFile enter

wait...

and then keeps on running , doesn't do anything, it seems to me HandleFileAsync never returns

public async Task  method1()
{
    Task<int> task =  HandleFileAsync();    
    log.Info("wait...");
    task.Wait();
    var x = task.Result;
    log.Info("print x.."+ x);
}


static async Task<int> HandleFileAsync()
{
    string file = @"C:\Users\..\..\text.txt";
    log.Info("HandleFile enter");
    int count = 0;

    // Read in the specified file.
    // ... Use async StreamReader method.
    using (StreamReader reader = new StreamReader(file))
    {
        string v = await reader.ReadToEndAsync();

        // ... Process the file data somehow.
        count += v.Length;

        // ... A slow-running computation.
        //     Dummy code.
        for (int i = 0; i < 1000; i++)
        {
            int x = v.GetHashCode();
            if (x == 0)
            {
                count--;
            }
        }  
    }
    log.Info("HandleFile exit");
    return count;
}

How do I make it run to print x?

Community
  • 1
  • 1
user1207289
  • 3,060
  • 6
  • 30
  • 66
  • 9
    My guess is you're running this in something like Windows Forms or WPF. When you call `task.Wait()` you're *blocking* the UI thread - it can't make any more progress, which means the next `HandleFIleAsync` continuation can't run. Just use `await task` instead of `task.Wait()`. You almost *never* want to use `Task.Wait()` or `Task.Result`. – Jon Skeet Oct 07 '19 at 17:59
  • Try putting an exception handler around all of your code. I find that unhandled exceptions in async code can manifest like that in the VS debugger. – Eric J. Oct 07 '19 at 18:00
  • 1
    @Jon Skeet that was it , `await task` . thank you so much! – user1207289 Oct 07 '19 at 18:02

1 Answers1

0

Looking at the methods you shared, the async/await looks a little awkward.

deleted the 1st note and changed the void back to Task. Since you are learning, these things are important.

2nd remove the task.wait command, use await. see the changes I have made below.

public async Task method1()
{
    log.info('Starting process');
    int task = await HandleFileAsync();    
    log.Info("print x.."+ task);
}

I had ran into the following Getting Started with Async / Await. The blog post is related to Xamarin, but it explain the async/await pattern really well. I hope it helps.

Neil
  • 629
  • 5
  • 14