簡體   English   中英

有沒有辦法使用舊的 .net 框架版本異步寫入 FileStream?

[英]Is there any way for writing into a FileStream asynchronously with older .net framework version?

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

我的問題是,為了使用異步,我需要 .NET 框架 4.5 或更高版本,但我希望能夠在以前的 .NET 框架版本上做同樣的事情(異步寫入 FileStream)。

目前我有一個帶有事件處理程序的 static 觀察者 class 。 此事件處理程序與每次創建某個 class 時調用的事件相關聯。 此事件將調用以下 function:

    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 框架版本一起使用?

.NET 框架支持異步 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM