如何异步Files.ReadAllLines指日可待的结果? [英] How to Async Files.ReadAllLines and await for results?

查看:186
本文介绍了如何异步Files.ReadAllLines指日可待的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code,

    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;
    }

Words.txt 有一吨,我读到s变量的话,我想利用的异步的await 在C#中5个关键字使用异步CTP库所以WPF应用程序不会挂起。到目前为止,我有以下的code,

Words.txt has a ton of words which i read into the s variable, I am trying to make use of async and await keywords in C# 5 using Async CTP Library so the WPF app doesn't hang. So far I have the following code,

    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();  // what more do i do here apart from having the await keyword?
        // do something with s

        button1.IsEnabled = true;
    }

我们的目标是读取文件中的异步,而不是同步,以避免WPF应用程序的冻结。

The goal is to read the file in async rather than sync, to avoid freezing of WPF app.

任何帮助是AP preciated,谢谢!

Any help is appreciated, Thanks!

推荐答案

使用 Task.Run ,它本质上是一个包装 Task.Factory .StartNew ,异步包装是$ C $ ç闻

Using Task.Run, which essentially is a wrapper for Task.Factory.StartNew, for asynchronous wrappers is a code smell.

如果你不想使用阻断功能浪费CPU线程,你应该等待一个真正的异步IO方法,<一个href=\"http://msdn.microsoft.com/en-us/library/system.io.streamreader.readtoendasync.aspx\"><$c$c>StreamReader.ReadToEndAsync,像这样的:

If you don't want to waste a CPU thread by using a blocking function, you should await a truly asynchronous IO method, StreamReader.ReadToEndAsync, like this:

using (var reader = File.OpenText("Words.txt"))
{
    var fileText = await reader.ReadToEndAsync();
    // Do something with fileText...
}

这将得到整个文件作为字符串,而不是列表&LT;串&GT; 。如果你需要,而不是线,你可以很容易事后分割字符串,就像这样:

This will get the whole file as a string instead of a List<string>. If you need lines instead, you could easily split the string afterwards, like this:

using (var reader = File.OpenText("Words.txt"))
{
    var fileText = await reader.ReadToEndAsync();
    return fileText.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
}

修改:这是实现几乎相同的code作为 File.ReadAllLines 的方法。在code是基于<一实施href=\"http://referencesource.microsoft.com/#mscorlib/system/io/file.cs,8d10107b7a92c5c2\"><$c$c>File.ReadAllLines:

EDIT: Here's a method to achieve almost the same code as File.ReadAllLines. The code is based on the implementation of File.ReadAllLines:

public static class FileEx
{
    public static Task<string[]> ReadAllLinesAsync(string path)
    {
        return ReadAllLinesAsync(path, Encoding.UTF8);
    }

    public static async Task<string[]> ReadAllLinesAsync(string path, Encoding encoding)
    {
        var lines = new List<string>();

        using (var reader = new StreamReader(path, encoding))
        {
            string line;
            while ((line = await reader.ReadLineAsync()) != null)
            {
                lines.Add(line);
            }
        }

        return lines.ToArray();
    }
}

这篇关于如何异步Files.ReadAllLines指日可待的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆