相关疑难解决方法(0)

如何异步Files.ReadAllLines并等待结果?

我有以下代码,

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        button1.IsEnabled = false;

        var s = File.ReadAllLines("Words.txt").ToList(); // my WPF app hangs here
        // do something with s

        button1.IsEnabled = true;
    }
Run Code Online (Sandbox Code Playgroud)

Words.txt有很多单词,我读入s变量,我试图利用C#5中的asyncawait关键字,Async CTP Library所以WPF应用程序不会挂起.到目前为止,我有以下代码,

    private async void button1_Click(object sender, RoutedEventArgs e)
    {
        button1.IsEnabled = false;

        Task<string[]> ws = Task.Factory.FromAsync<string[]>(
            // What do i have here? there are so many overloads
            ); // is this the right way to do?

        var s = await File.ReadAllLines("Words.txt").ToList(); …
Run Code Online (Sandbox Code Playgroud)

.net c# asynchronous async-await c#-5.0

62
推荐指数
1
解决办法
4万
查看次数

为什么 File.ReadAllLinesAsync() 会阻塞 UI 线程?

这是我的代码。读取文件行的​​ WPF 按钮的事件处理程序:

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
}
Run Code Online (Sandbox Code Playgroud)

File.ReadAllLines()在 .NET Core 3.1 WPF App 中使用了异步版本的方法。

但它阻塞了 UI 线程!为什么?


更新:与@Theodor Zoulias 相同,我做了一个测试:

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 …
Run Code Online (Sandbox Code Playgroud)

c# wpf asynchronous async-await .net-core-3.1

4
推荐指数
1
解决办法
620
查看次数

标签 统计

async-await ×2

asynchronous ×2

c# ×2

.net ×1

.net-core-3.1 ×1

c#-5.0 ×1

wpf ×1