Here is my code. An event handler for WPF button that reads lines of a file:
private async void Button_OnClick(object sender, RoutedEventArgs e)
{
Button.Content = "Loading...";
var lines = await File.ReadAllLinesAsync(@"D:\temp.txt"); //Why blocking UI Thread???
Button.Content = "Show"; //Reset Button text
}
I used asynchronous version of File.ReadAllLines()
method in .NET Core 3.1 WPF App.
But it is blocking the UI Thread! Why?
Update: Same as @Theodor Zoulias, I do a test :
private async void Button_OnClick(object sender, RoutedEventArgs e)
{
Button.Content = "Loading...";
TextBox.Text = "";
var stopwatch = Stopwatch.StartNew();
var task = File.ReadAllLinesAsync(@"D:\temp.txt"); //Problem
var duration1 = stopwatch.ElapsedMilliseconds;
var isCompleted = task.IsCompleted;
stopwatch.Restart();
var lines = await task;
var duration2 = stopwatch.ElapsedMilliseconds;
Debug.WriteLine($"Create: {duration1:#,0} msec, Task.IsCompleted: {isCompleted}");
Debug.WriteLine($"Await: {duration2:#,0} msec, Lines: {lines.Length:#,0}");
Button.Content = "Show";
}
Result is :
Create: 652 msec msec, Task.IsCompleted: False | Await: 15 msec, Lines: 480,001
.NET Core 3.1, C# 8, WPF, Debug build | 7.32 Mb File(.txt) | HDD 5400 SATA
ReadAllLines
. He is using the Asynchronous version and it still hangs (which should be impossible, so i am going to assume something else is causing issues) – Spanosvar lines = await Task.Run(() => File.ReadAllLines(@"D:\temp.txt"));
as suggested in answer, it's not only keeps UI responsive, it's 7x faster thanReadAllLinesAsync
! – Formative