// From LinkedIn Learning course: From the course: Async Programming in C# // https://www.linkedin.com/learning/async-programming-in-c-sharp?u=2374954 // and from // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/using-async-for-file-access //-// lines commented like this refer to MS-only sections of the code (ie. only works in Visual Studio) using System; using System.IO; using System.Threading; using System.Text; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; // using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Networking { public class AsyncFiles { public async Task ProcessRead(string filePath) { // string filePath = @"temp.txt"; Console.WriteLine("ProcessRead: Begin"); if (File.Exists(filePath) == false) { Console.WriteLine("file not found: " + filePath); } else { try { string text = await ReadTextAsync(filePath); Console.WriteLine(text); } catch (Exception ex) { Console.WriteLine(ex.Message); } } Console.WriteLine("ProcessRead: End"); } private async Task ReadTextAsync(string filePath) { using (FileStream sourceStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true)) { StringBuilder sb = new StringBuilder(); byte[] buffer = new byte[0x1000]; int numRead; while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0) { string text = Encoding.Unicode.GetString(buffer, 0, numRead); sb.Append(text); } // Thread.Sleep(5000); return sb.ToString(); } } public async Task DoIt(params string[] strs){ Task t; List tasks = new List(); foreach (string str in strs) { t = ProcessRead(str); tasks.Add(t); } await Task.WhenAll(tasks); } } public class Tester { public static void Main(){ AsyncFiles afs = new AsyncFiles(); Console.WriteLine("Main: before ProcessRead()"); afs.DoIt("temp.txt", "tmp.txt"); Console.WriteLine("Main: after ProcessRead()"); //t.ProcessWriteMult(); } } }