Home:ALL Converter>Proper way to read files asynchronously

Proper way to read files asynchronously

Ask Time:2020-01-12T11:34:27         Author:Trax

Json Formatter

I'm trying to read files asynchronously. I was wondering if this is a proper way to do so. Below is what I have tried so far. Is this correct?

static void Main(string[] args)
{
     Task<string> readFileTask = Task.Run(() => ReadFile(@"C:\Users\User\Desktop\Test.txt"));
     readFileTask.Wait();
     string astr = readFileTask.Result;
     Console.WriteLine(astr);
}

static private async Task<string> ReadFile(string filePath)
{
     string text = File.ReadAllText(filePath);
     return text;
}

Thanks.

Author:Trax,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/59700704/proper-way-to-read-files-asynchronously
habib :

System.IO provides File.ReadAllTextAsync method for .Net Standard > 2.1 and .NET Core 2.0. \nIf you are using C# 7.1 or higher you can use File.ReadAllTextAsync inside Main function directly.\n\nstatic async Task Main(string[] args)\n{\n var astr = await File.ReadAllTextAsync(@\"C:\\Users\\User\\Desktop\\Test.txt\");\n Console.WriteLine(astr);\n}\n\n\nUnfortunately, If you are not using C# 7.1 or higher then you can't use Async Main. You have to use Task.Run to calll async methods.\n\nstatic void Main(string[] args)\n{\n var astr=Task.Run(async () =>\n {\n return await File.ReadAllTextAsync(@\"C:\\Users\\User\\Desktop\\Test.txt\");\n }).GetAwaiter().GetResult();\n\n Console.WriteLine(astr);\n }\n\n\nIn case you are using .NET Framework then you have to use FileStream because System.IO not provides File.ReadAllTextAsync method.\n\nprivate static async Task<string> ReadAllTextAsync(string filePath) \n{ \n using (FileStream sourceStream = new FileStream(filePath, \n FileMode.Open, FileAccess.Read, FileShare.Read, \n bufferSize: 4096, useAsync: true)) \n { \n StringBuilder sb = new StringBuilder(); \n\n byte[] buffer = new byte[0x1000]; \n int numRead; \n while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0) \n { \n string text = Encoding.Unicode.GetString(buffer, 0, numRead); \n sb.Append(text); \n } \n\n return sb.ToString(); \n } \n} \n",
2020-01-12T04:56:33
yy