FileStream.ReadAsync 方法

定義

多載

ReadAsync(Memory<Byte>, CancellationToken)

以非同步方式從目前的檔案資料流讀取位元組序列、將其寫入記憶體區域、依讀取的位元組數將檔案資料流中位置往前移,並監視取消要求。

ReadAsync(Byte[], Int32, Int32, CancellationToken)

以非同步方式從目前的檔案資料流讀取位元組序列、將其寫入位元組陣列 (從指定的位移開始)、依讀取的位元組數將檔案資料流中位置往前移,並監視取消要求。

ReadAsync(Memory<Byte>, CancellationToken)

來源:
FileStream.cs
來源:
FileStream.cs
來源:
FileStream.cs

以非同步方式從目前的檔案資料流讀取位元組序列、將其寫入記憶體區域、依讀取的位元組數將檔案資料流中位置往前移,並監視取消要求。

public override System.Threading.Tasks.ValueTask<int> ReadAsync (Memory<byte> buffer, System.Threading.CancellationToken cancellationToken = default);
override this.ReadAsync : Memory<byte> * System.Threading.CancellationToken -> System.Threading.Tasks.ValueTask<int>
Public Overrides Function ReadAsync (buffer As Memory(Of Byte), Optional cancellationToken As CancellationToken = Nothing) As ValueTask(Of Integer)

參數

buffer
Memory<Byte>

寫入資料的緩衝區。

cancellationToken
CancellationToken

用來監視是否有取消要求的語彙基元。 預設值是 None

傳回

表示非同步讀取作業並會將位元組總數包裝到緩衝區的工作。 如果目前可供使用的位元組數目少於所要求的數目,結果值可能會小於所要求的位元組數目,或者如果已經到達資料流末端,則可能為 0 (零)。

例外狀況

取消權杖已取消。 此例外狀況會儲存在傳回的工作中。

範例

下列範例示範如何以非同步方式從檔案讀取。

using System;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.IO;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string filename = @"c:\Temp\userinputlog.txt";
            byte[] result;

            using (FileStream SourceStream = File.Open(filename, FileMode.Open))
            {
                result = new byte[SourceStream.Length];
                await SourceStream.ReadAsync(result, 0, (int)SourceStream.Length);
            }

            UserInput.Text = System.Text.Encoding.ASCII.GetString(result);
        }
    }
}
open System.Text
open System.IO

let read () =
    task {
        let filename = @"c:\Temp\userinputlog.txt"
        use sourceStream = File.Open(filename, FileMode.Open)
        let length = int sourceStream.Length    
        let result = Array.zeroCreate length 
        let! _ = sourceStream.ReadAsync(result, 0, length)
        return Encoding.ASCII.GetString result
    }

let main =
    task {
        let! text = read ()
        printfn $"{text}"
    }    
main.Wait()
Imports System.IO
Imports System.Text

Class MainWindow
    Private Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
        Dim filename As String = "c:\Temp\userinputlog.txt"

        Dim result As Byte()

        Using SourceStream As FileStream = File.Open(filename, FileMode.Open)
            result = New Byte(SourceStream.Length - 1) {}
            Await SourceStream.ReadAsync(result, 0, CType(SourceStream.Length, Integer))
        End Using

        UserInput.Text = System.Text.Encoding.ASCII.GetString(result)
    End Sub
End Class

備註

方法 ReadAsync 可讓您執行需要大量資源的檔案作業,而不會封鎖主執行緒。 這項效能考量對於 Windows 8.x Store 應用程式或傳統型應用程式而言特別重要,尤其是針對耗時的資料流作業可能會阻礙 UI 執行緒,使應用程式看起來像是停止運作的情況。 非同步方法會與 async Visual Basic 和 C# 中的 和 await 關鍵字搭配使用。

CanRead使用 屬性來判斷目前實例是否支援讀取。

如果作業在完成之前取消,則傳回的工作會 TaskStatus.Canceled 包含 屬性的值 Status 。 如果處置檔案的控制碼,傳回的工作會在 ObjectDisposedException 屬性中包含 Task.Exception 例外狀況。

適用於

ReadAsync(Byte[], Int32, Int32, CancellationToken)

來源:
FileStream.cs
來源:
FileStream.cs
來源:
FileStream.cs

以非同步方式從目前的檔案資料流讀取位元組序列、將其寫入位元組陣列 (從指定的位移開始)、依讀取的位元組數將檔案資料流中位置往前移,並監視取消要求。

public:
 override System::Threading::Tasks::Task<int> ^ ReadAsync(cli::array <System::Byte> ^ buffer, int offset, int count, System::Threading::CancellationToken cancellationToken);
public override System.Threading.Tasks.Task<int> ReadAsync (byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken);
[System.Runtime.InteropServices.ComVisible(false)]
public override System.Threading.Tasks.Task<int> ReadAsync (byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken);
override this.ReadAsync : byte[] * int * int * System.Threading.CancellationToken -> System.Threading.Tasks.Task<int>
[<System.Runtime.InteropServices.ComVisible(false)>]
override this.ReadAsync : byte[] * int * int * System.Threading.CancellationToken -> System.Threading.Tasks.Task<int>
Public Overrides Function ReadAsync (buffer As Byte(), offset As Integer, count As Integer, cancellationToken As CancellationToken) As Task(Of Integer)

參數

buffer
Byte[]

寫入資料的緩衝區。

offset
Int32

開始於此處自資料流寫入資料的 buffer 中的位元組位移。

count
Int32

要讀取的最大位元組數。

cancellationToken
CancellationToken

用來監視是否有取消要求的語彙基元。

傳回

表示非同步讀取作業並會將位元組總數包裝到緩衝區的工作。 如果目前可供使用的位元組數目少於所要求的數目,結果值可能會小於所要求的位元組數目,或者如果已經到達資料流末端,則可能為 0 (零)。

屬性

例外狀況

buffernull

offsetcount 為負。

offsetcount 的總和大於緩衝區長度。

資料流不支援讀取。

資料流已經處置。

之前的讀取作業目前正在使用資料流。

取消權杖已取消。 此例外狀況會儲存在傳回的工作中。

範例

下列範例示範如何以非同步方式從檔案讀取。

using System;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.IO;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string filename = @"c:\Temp\userinputlog.txt";
            byte[] result;

            using (FileStream SourceStream = File.Open(filename, FileMode.Open))
            {
                result = new byte[SourceStream.Length];
                await SourceStream.ReadAsync(result, 0, (int)SourceStream.Length);
            }

            UserInput.Text = System.Text.Encoding.ASCII.GetString(result);
        }
    }
}
open System.Text
open System.IO

let read () =
    task {
        let filename = @"c:\Temp\userinputlog.txt"
        use sourceStream = File.Open(filename, FileMode.Open)
        let length = int sourceStream.Length    
        let result = Array.zeroCreate length 
        let! _ = sourceStream.ReadAsync(result, 0, length)
        return Encoding.ASCII.GetString result
    }

let main =
    task {
        let! text = read ()
        printfn $"{text}"
    }    
main.Wait()
Imports System.IO
Imports System.Text

Class MainWindow
    Private Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
        Dim filename As String = "c:\Temp\userinputlog.txt"

        Dim result As Byte()

        Using SourceStream As FileStream = File.Open(filename, FileMode.Open)
            result = New Byte(SourceStream.Length - 1) {}
            Await SourceStream.ReadAsync(result, 0, CType(SourceStream.Length, Integer))
        End Using

        UserInput.Text = System.Text.Encoding.ASCII.GetString(result)
    End Sub
End Class

備註

方法 ReadAsync 可讓您執行需要大量資源的檔案作業,而不會封鎖主執行緒。 這項效能考量對於 Windows 8.x Store 應用程式或傳統型應用程式而言特別重要,尤其是針對耗時的資料流作業可能會阻礙 UI 執行緒,使應用程式看起來像是停止運作的情況。 非同步方法會與 async Visual Basic 和 C# 中的 和 await 關鍵字搭配使用。

CanRead使用 屬性來判斷目前實例是否支援讀取。

如果作業在完成之前取消,則傳回的工作會 TaskStatus.Canceled 包含 屬性的值 Task.Status 。 如果處置檔案的控制碼,傳回的工作會在 ObjectDisposedException 屬性中包含 Task.Exception 例外狀況。

這個方法會儲存在工作中,它會傳回方法同步對應專案可以擲回的所有非使用狀況例外狀況。 如果例外狀況儲存在傳回的工作中,則會在等候工作時擲回該例外狀況。 使用狀況例外狀況,例如 ArgumentException ,仍會同步擲回。 如需預存的例外狀況,請參閱 所 Read(Byte[], Int32, Int32) 擲回的例外狀況。

另請參閱

適用於