简体   繁体   English

异步等待调用在我的控制台应用程序中无法正常工作

[英]Async await call is not working properly in my Console Application

Async await call is not working properly in my code.异步等待调用在我的代码中无法正常工作。

static void Main(string[] args)
{
    // Start the HandleFile method.
    Task<int> task = HandleFileAsync();

    // Control returns here before HandleFileAsync returns.
    // ... Prompt the user.
    Console.WriteLine("Please wait patiently " +
        "while I do something important.");

    // Do something at the same time as the file is being read.
    string line = Console.ReadLine();
    Console.WriteLine("You entered (asynchronous logic): " + line);

    // Wait for the HandleFile task to complete.
    // ... Display its results.
    task.Wait();
    var x = task.Result;
    Console.WriteLine("Count: " + x);

    Console.WriteLine("[DONE]");
    Console.ReadLine();
}

static async Task<int> HandleFileAsync()
{
    string file = @"C:\testfile.txt";
    Console.WriteLine("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 < 10000; i++)
        {
            int x = v.GetHashCode();
            if (x == 0)
            {
                count--;
            }
        }
    }
    Console.WriteLine("HandleFile exit");
    return count;
}

Its expected output should be其预期的 output 应该是

HandleFile enter处理文件进入

Please wait patiently while I do something important请耐心等待,我正在做重要的事情

HandleFile exit处理文件退出

but output is coming但是 output 来了

HandleFile enter处理文件进入

HandleFile exit处理文件退出

Please wait patiently while I do something important请耐心等待,我正在做重要的事情

Your question have no issue, I checked It by running your code in my PC.你的问题没有问题,我通过在我的电脑上运行你的代码来检查它。 Please once again check your console application creating method.请再次检查您的控制台应用程序创建方法。 If there is problem, please share the detail of creating your application method as well.如果有问题,请分享创建您的应用程序方法的详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM