NetworkStream.ReadTimeout 屬性

定義

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

public:
 virtual property int ReadTimeout { int get(); void set(int value); };
public override int ReadTimeout { get; set; }
member this.ReadTimeout : int with get, set
Public Overrides Property ReadTimeout As Integer

屬性值

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

例外狀況

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

範例

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

// 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 方法所執行的異步讀取。

適用於