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
HandleFile enter
Please wait patiently while I do something important
HandleFile exit
but output is coming
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.