NetworkStream.ReadTimeout 屬性

定義

取得或設定讀取作業封鎖等待資料的時間長度。

C#
public override int ReadTimeout { get; set; }

屬性值

Int32,指定讀取作業失敗前經過的時間長度 (以毫秒為單位)。 預設值 Infinite 會指定讀取作業不逾時。

例外狀況

指定的值小於或等於零,並且不是 Infinite

範例

下列程式代碼範例會將網路數據流的讀取逾時設定為10毫秒。

C#
// Create a client that will connect to a
// server listening on the contosoServer computer
// at port 11000.
TcpClient tcpClient = new TcpClient();
tcpClient.Connect("contosoServer", 11000);
// Get the stream used to read the message sent by the server.
NetworkStream networkStream = tcpClient.GetStream();
// Set a 10 millisecond timeout for reading.
networkStream.ReadTimeout = 10;
// Read the server message into a byte buffer.
byte[] bytes = new byte[1024];
networkStream.Read(bytes, 0, 1024);
//Convert the server's message into a string and display it.
string data = Encoding.UTF8.GetString(bytes);
Console.WriteLine("Server sent message: {0}", data);
networkStream.Close();
tcpClient.Close();

備註

如果讀取作業未在此屬性指定的時間內完成,讀取作業會 IOException擲回 。

備註

此屬性只會影響呼叫 Read 方法所執行的同步讀取。 這個屬性不會影響呼叫 BeginReadReadAsync 方法所執行的異步讀取。

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1