【问题标题】:Is there any way for writing into a FileStream asynchronously with older .net framework version?有什么方法可以使用旧的 .net 框架版本异步写入 FileStream 吗?
【发布时间】:2020-06-10 17:15:48
【问题描述】:

Async 和 await 运算符是在 C# 5 和 .NET Framework 4.5 中引入的。

我的问题是,为了使用异步,我需要 .NET Framework 4.5 或更高版本,但我希望能够在以前的 .NET Framework 版本上执行相同的操作(异步写入 FileStream)。

目前我有一个带有事件处理程序的静态观察者类。此事件处理程序与每次创建某个类时都会调用的事件相关联。该事件将调用以下函数:

    static async void FileWriter(string path, string fileName, byte[] text)
    {
        byte[] encodedText = Encoding.Convert(Encoding.Unicode, Encoding.GetEncoding(437), text);

        using (FileStream sourceStream = new FileStream(Path.Combine(path, fileName),
            FileMode.Append, FileAccess.Write, FileShare.None,
            bufferSize: 4096, useAsync: true))
        {
            await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
        };
    }

是否有任何替代方法可以使其适用于较旧的 .NET Framework 版本?

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    .NET Framework 支持异步 I/O 的时间比 C# 的 async/await 关键字要长得多。您可以使用 APM 方法:Stream.BeginWriteStream.BeginRead 等。

    不过,这些使用起来不是很友好。相当于您的示例:

    byte[] encodedText = ...;
    FileStream sourceStream = ...;
    
    sourceStream.BeginWrite(encodedText, 0, encodedText.Length, res =>
    {
       try
       {
          // result of Write op materializes here -- exception etc.
          sourceStream.EndWrite(res);
       }
       finally
       {
          sourceStream.Dispose();
       }
    }, state: null);
    

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2012-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多