Stream.ReadAsync 方法

定义

从当前流异步读取字节序列,并将流中的位置提升读取的字节数。Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

重载

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

从当前流异步读取字节的序列,将流中的位置提升读取的字节数,并监视取消请求。Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

ReadAsync(Memory<Byte>, CancellationToken)

从当前流异步读取字节的序列,将流中的位置提升读取的字节数,并监视取消请求。Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

ReadAsync(Byte[], Int32, Int32)

从当前流异步读取字节序列,并将流中的位置提升读取的字节数。Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

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

从当前流异步读取字节的序列,将流中的位置提升读取的字节数,并监视取消请求。Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

public:
 virtual System::Threading::Tasks::Task<int> ^ ReadAsync(cli::array <System::Byte> ^ buffer, int offset, int count, System::Threading::CancellationToken cancellationToken);
public virtual System.Threading.Tasks.Task<int> ReadAsync (byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken);
[System.Runtime.InteropServices.ComVisible(false)]
public virtual System.Threading.Tasks.Task<int> ReadAsync (byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken);
abstract member ReadAsync : byte[] * int * int * System.Threading.CancellationToken -> System.Threading.Tasks.Task<int>
override this.ReadAsync : byte[] * int * int * System.Threading.CancellationToken -> System.Threading.Tasks.Task<int>

参数

buffer
Byte[]

要写入数据的缓冲区。The buffer to write the data into.

offset
Int32

buffer 中的字节偏移量,从该偏移量开始写入从流中读取的数据。The byte offset in buffer at which to begin writing data from the stream.

count
Int32

最多读取的字节数。The maximum number of bytes to read.

cancellationToken
CancellationToken

要监视取消请求的标记。The token to monitor for cancellation requests. 默认值是 NoneThe default value is None.

返回

表示异步读取操作的任务。A task that represents the asynchronous read operation. TResult 参数的值包含读入缓冲区的总字节数。The value of the TResult parameter contains the total number of bytes read into the buffer. 如果当前可用字节数少于所请求的字节数,则该结果值可小于所请求的字节数;如果已到达流结尾时,则为 0(零)。The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached.

属性

例外

buffernullbuffer is null.

offsetcount 为负数。offset or count is negative.

offsetcount 的总和大于缓冲区长度。The sum of offset and count is larger than the buffer length.

流不支持读取。The stream does not support reading.

已释放流。The stream has been disposed.

之前的读取操作当前正在使用流。The stream is currently in use by a previous read operation.

注解

利用 ReadAsync 方法,你可以在不阻塞主线程的情况下执行占用大量资源的 i/o 操作。The ReadAsync method enables you to perform resource-intensive I/O operations without blocking the main thread. Windows 8.x 应用商店Windows 8.x Store 应用或 桌面desktop 应用中一个耗时的流操作可能阻塞 UI 线程并让您的应用看起来好像不工作时,这种性能的考虑就显得尤为重要了。This performance consideration is particularly important in a Windows 8.x 应用商店Windows 8.x Store app or 桌面desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. 异步方法与 Visual Basic 和C#中的 asyncawait 关键字结合使用。The async methods are used in conjunction with the async and await keywords in Visual Basic and C#.

使用 CanRead 属性可确定当前实例是否支持读取。Use the CanRead property to determine whether the current instance supports reading.

如果在操作完成前取消该操作,则返回的任务将包含 Status 属性的 Canceled 值。If the operation is canceled before it completes, the returned task contains the Canceled value for the Status property.

有关示例,请参阅 ReadAsync(Byte[], Int32, Int32) 重载。For an example, see the ReadAsync(Byte[], Int32, Int32) overload.

另请参阅

ReadAsync(Memory<Byte>, CancellationToken)

从当前流异步读取字节的序列,将流中的位置提升读取的字节数,并监视取消请求。Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

public virtual System.Threading.Tasks.ValueTask<int> ReadAsync (Memory<byte> buffer, System.Threading.CancellationToken cancellationToken = default);
abstract member ReadAsync : Memory<byte> * System.Threading.CancellationToken -> System.Threading.Tasks.ValueTask<int>
override this.ReadAsync : Memory<byte> * System.Threading.CancellationToken -> System.Threading.Tasks.ValueTask<int>

参数

buffer
Memory<Byte>

要将数据写入的内存区域。The region of memory to write the data into.

cancellationToken
CancellationToken

要监视取消请求的标记。The token to monitor for cancellation requests. 默认值是 NoneThe default value is None.

返回

表示异步读取操作的任务。A task that represents the asynchronous read operation. Result 属性的值包含读入缓冲区的总字节数。The value of its Result property contains the total number of bytes read into the buffer. 如果很多字节当前不可用,则结果值可小于在缓冲区中分配的字节数;如果已到达流结尾,则结果值可以为 0(零)。The result value can be less than the number of bytes allocated in the buffer if that many bytes are not currently available, or it can be 0 (zero) if the end of the stream has been reached.

注解

利用 ReadAsync 方法,你可以在不阻塞主线程的情况下执行占用大量资源的 i/o 操作。The ReadAsync method enables you to perform resource-intensive I/O operations without blocking the main thread. Windows 8.x 应用商店Windows 8.x Store 应用或 桌面desktop 应用中一个耗时的流操作可能阻塞 UI 线程并让您的应用看起来好像不工作时,这种性能的考虑就显得尤为重要了。This performance consideration is particularly important in a Windows 8.x 应用商店Windows 8.x Store app or 桌面desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. 异步方法与 Visual Basic 和C#中的 asyncawait 关键字结合使用。The async methods are used in conjunction with the async and await keywords in Visual Basic and C#.

使用 CanRead 属性可确定当前实例是否支持读取。Use the CanRead property to determine whether the current instance supports reading.

如果在操作完成前取消该操作,则返回的任务将包含 Status 属性的 TaskStatus.Canceled 值。If the operation is canceled before it completes, the returned task contains the TaskStatus.Canceled value for the Status property.

有关示例,请参阅 ReadAsync(Byte[], Int32, Int32) 重载。For an example, see the ReadAsync(Byte[], Int32, Int32) overload.

ReadAsync(Byte[], Int32, Int32)

从当前流异步读取字节序列,并将流中的位置提升读取的字节数。Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

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

参数

buffer
Byte[]

要写入数据的缓冲区。The buffer to write the data into.

offset
Int32

buffer 中的字节偏移量,从该偏移量开始写入从流中读取的数据。The byte offset in buffer at which to begin writing data from the stream.

count
Int32

最多读取的字节数。The maximum number of bytes to read.

返回

表示异步读取操作的任务。A task that represents the asynchronous read operation. TResult 参数的值包含读入缓冲区的总字节数。The value of the TResult parameter contains the total number of bytes read into the buffer. 如果当前可用字节数少于所请求的字节数,则该结果值可小于所请求的字节数;如果已到达流结尾时,则为 0(零)。The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached.

属性

例外

buffernullbuffer is null.

offsetcount 为负数。offset or count is negative.

offsetcount 的总和大于缓冲区长度。The sum of offset and count is larger than the buffer length.

流不支持读取。The stream does not support reading.

已释放流。The stream has been disposed.

之前的读取操作当前正在使用流。The stream is currently in use by a previous read operation.

示例

下面的示例演示如何以异步方式从文件读取。The following example shows how to read from a file asynchronously. 该示例使用派生自 Stream 类的 FileStream 类。The example uses the FileStream class, which derives from the Stream class.

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);
        }
    }
}
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 方法,你可以在不阻塞主线程的情况下执行占用大量资源的 i/o 操作。The ReadAsync method enables you to perform resource-intensive I/O operations without blocking the main thread. Windows 8.x 应用商店Windows 8.x Store 应用或 桌面desktop 应用中一个耗时的流操作可能阻塞 UI 线程并让您的应用看起来好像不工作时,这种性能的考虑就显得尤为重要了。This performance consideration is particularly important in a Windows 8.x 应用商店Windows 8.x Store app or 桌面desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. 异步方法与 Visual Basic 和C#中的 asyncawait 关键字结合使用。The async methods are used in conjunction with the async and await keywords in Visual Basic and C#.

使用 CanRead 属性可确定当前实例是否支持读取。Use the CanRead property to determine whether the current instance supports reading.

适用于