0

I'm using .Net core 3.1 and the method File.ReadAllLinesAsync blocks UI thread in wpf when awaiting it, so I took a look at the source code of this method (here) and saw that it uses async methods of StreamReader class. So I'm wondering if it is normal and if it is why ? Thanks in advance, here is my code:

private async void LoadFileButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog()
            {
                Multiselect = false,
                DefaultExt = "txt",
                Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
            };
            var b = fileDialog.ShowDialog();
            if (!b.HasValue || !b.Value)
                return;
            var l = await File.ReadAllLinesAsync(fileDialog.FileName, Encoding.UTF8);

        }

edit: Well I just tried the following code :

using (var reader = File.OpenText(fileDialog.FileName))
            {
                l = await reader.ReadToEndAsync();
                
            }

and it worked without blocking UI thread. So I'm starting to think if maybe the File.ReadAllLinesAsync method is broken.

LilCoding
  • 71
  • 5
  • Try using `await File.ReadAllLinesAsync(fileDialog.FileName, Encoding.UTF8).ConfigureAwait(false)` – Alex Jun 13 '21 at 16:49
  • @AlexBakanov thanks but same issue is happening. – LilCoding Jun 13 '21 at 17:35
  • How about `var l = await Task.Run(() => File.ReadAllLines(fileDialog.FileName, Encoding.UTF8));`? Does that also block? – Clemens Jun 13 '21 at 17:56
  • 1
    @Clemens this indeed work but I'm trying to understand why the File.ReadAllLinesAsync blocks UI thread whereas from what I see in the source code of this method it shouldn't. – LilCoding Jun 13 '21 at 18:09
  • You're awaiting ReadAllLinesAsync method, so main thread will wait for the result of ReadAllLinesAsync which freeze the UI. Solution is using a background thread/task or using a BackgroundWorker. My recommendation is using a thread/task as you've more control and also it's professional. – Saeed Aghdam Jun 14 '21 at 05:20

0 Answers0