Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm stuck with .NET 4.0 on a project. StreamReader offers no Async or Begin/End version of ReadLine. The underlying Stream object has BeginRead/BeginEnd but these take a byte array so I'd have to implement the logic for reading line by line.

Is there something in the 4.0 Framework to achieve this?

like image 585
Asik Avatar asked Nov 08 '22 06:11

Asik


1 Answers

You can use Task. You don't specify other part of your code so I don't know what you want to do. I advise you to avoid using Task.Wait because this is blocking the UI thread and waiting for the task to finish, which became not really async ! If you want to do some other action after the file is readed in the task, you can use task.ContinueWith.

Here full example, how to do it 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();
    }
like image 117
mybirthname Avatar answered Nov 14 '22 23:11

mybirthname