Is there a .NET 4.0 replacement for StreamReader.ReadLineAsync?

I am stuck with .NET 4.0 in a project. StreamReader does not offer a ReadLine version for Async or Begin / End. The main Stream object has a BeginRead / BeginEnd, but they take a byte array, so I will have to implement logic to read line by line.

Is there anything in the 4.0 Framework for this?

+5
source share
2 answers

You can use Task . You do not specify another part of your code, so I do not know what you want to do. I recommend avoiding the use of Task.Wait , because it blocks the user interface thread and waits for the task to complete, which is not very asynchronous! If you want to perform some other actions after reading the file in the task, you can use task.ContinueWith .

Here's a complete example of how to do this without blocking the UI thread

  static void Main(string[] args) { string filePath = @"FILE PATH"; Task<string[]> task = Task.Run<string[]>(() => ReadFile(filePath)); bool stopWhile = false; //if you want to not block the UI with Task.Wait() for the result // and you want to perform some other operations with the already read file Task continueTask = task.ContinueWith((x) => { string[] result = x.Result; //result of readed file foreach(var a in result) { Console.WriteLine(a); } stopWhile = true; }); //here do other actions not related with the result of the file content while(!stopWhile) { Console.WriteLine("TEST"); } } public static string[] ReadFile(string filePath) { List<String> lines = new List<String>(); string line = ""; using (StreamReader sr = new StreamReader(filePath)) { while ((line = sr.ReadLine()) != null) lines.Add(line); } Console.WriteLine("File Readed"); return lines.ToArray(); } 
+1
source

You can use the parallel task library (TPL) to execute some kind of async behavior that you are trying to do.

Wrap the synchronous method in the task:

 var asyncTask = Task.Run(() => YourMethod(args, ...)); var asyncTask.Wait(); // You can also Task.WaitAll or other methods if you have several of these that you want to run in parallel. var result = asyncTask.Result; 

If you need to do this for StreamReader, you can continue to use this extension method for StreamReader if you want to simulate the usual methods of asynchronous use. Just take care of error handling and other errors using TPL.

0
source

Source: https://habr.com/ru/post/1259184/


All Articles