【问题标题】:Reading all lines from file asynchronously and safely异步安全地从文件中读取所有行
【发布时间】:2013-09-13 16:33:18
【问题描述】:

我正在尝试异步且安全地读取文件(寻求的最低权限级别)。我正在使用 .NET 3.5,找不到一个很好的例子(都使用 async 和 await)。

 public string GetLines()
    {
        var encoding = new UnicodeEncoding();
        byte[] allText;
        using (FileStream stream =File.Open(_path, FileMode.Open))
        {
            allText = new byte[stream.Length];
            //something like this, but does not compile in .net 3.5
            stream.ReadAsync(allText, 0, (int) allText.Length);
        }
        return encoding.GetString(allText);
    }  

问题是,我如何在 .net 3.5 中异步执行此操作,等到操作完成并将所有行发回给调用者?

调用者可以等到操作完成,但读取必须在后台线程中进行。

调用者是一个 UI 线程,我使用的是 .NET 3.5

【问题讨论】:

  • 您想异步执行,但要等到操作完成?
  • 您必须异步调用 GetLines。您无需在此处进行更改。
  • 是的,考虑到 UI 是调用者。

标签: c# io .net-3.5


【解决方案1】:

有多种选择,但最简单的方法是让此方法接受回调,然后在计算出给定值时调用它。调用者需要传入回调方法来处理结果,而不是阻塞在方法调用上:

public static void GetLines(Action<string> callback)
{
    var encoding = new UnicodeEncoding();
    byte[] allText;
    FileStream stream = File.Open(_path, FileMode.Open);
    allText = new byte[stream.Length];
    //something like this, but does not compile in .net 3.5
    stream.ReadAsync(allText, 0, (int)allText.Length);
    stream.BeginRead(allText, 0, allText.Length, result =>
    {
        callback(encoding.GetString(allText));
        stream.Dispose();
    }, null);
}

【讨论】:

    【解决方案2】:

    如果要等到操作完成,为什么需要异步呢?

    return File.ReadAllText(_path, new UnicodeEncoding());
    

    会成功的

    【讨论】:

      【解决方案3】:

      可能是这样的:

      GetLines(string path, ()=>
      {
          // here your code...
      });
      
      public void GetLines(string _path, Action<string> callback)
      {
          var result = string.Empty;
      
          new Action(() =>
          {
              var encoding = new UnicodeEncoding();
              byte[] allText;
              using (FileStream stream = File.Open(_path, FileMode.Open))
              {
                  allText = new byte[stream.Length];
                  //something like this, but does not compile in .net 3.5
                  stream.Read(allText, 0, (int)allText.Length);
              }
              result = encoding.GetString(allText);
          }).BeginInvoke(x => callback(result), null);
      }
      

      【讨论】:

        猜你喜欢
        • 2012-12-07
        • 1970-01-01
        • 1970-01-01
        • 2015-09-04
        • 1970-01-01
        • 2015-12-29
        • 1970-01-01
        • 2014-01-05
        • 1970-01-01
        相关资源
        最近更新 更多