NetworkStream.WriteTimeout 属性
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
获取或设置写入操作阻止等待数据的时间。
public:
virtual property int WriteTimeout { int get(); void set(int value); };
public override int WriteTimeout { get; set; }
member this.WriteTimeout : int with get, set
Public Overrides Property WriteTimeout As Integer
属性值
Int32 指定以毫秒为单位的时间量,表示写入操作失败前经过的时间。 默认值 Infinite 指定写入操作未超时。
例外
指定的值小于或等于零,并且不为 Infinite。
示例
下面的代码示例将网络流的写入超时设置为 10 毫秒。
#using <System.dll>
using namespace System;
using namespace System::Text;
using namespace System::Net;
using namespace System::Net::Sockets;
int main()
{
// Create the server side connection and
// start listening for clients.
TcpListener^ tcpListener = gcnew TcpListener(IPAddress::Any, 11000);
tcpListener->Start();
Console::WriteLine("Waiting for a connection....");
// Accept the pending client connection.
TcpClient^ tcpClient = tcpListener->AcceptTcpClient();
Console::WriteLine("Connection accepted.");
// Get the stream to write the message
// that will be sent to the client.
NetworkStream^ networkStream = tcpClient->GetStream();
String^ responseString = "Hello.";
// Set the write timeout to 10 millseconds.
networkStream->WriteTimeout = 10;
// Convert the message to a byte array and sent it to the client.
array<Byte>^ sendBytes = Encoding::UTF8->GetBytes(responseString);
networkStream->Write(sendBytes, 0, sendBytes->Length);
Console::WriteLine("Message Sent.");
// Close the connection to the client.
tcpClient->Close();
// Stop listening for incoming connections
// and close the server.
tcpListener->Stop();
// Dispose allocated resources.
delete networkStream;
delete tcpClient;
}
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Examples.System.Net
{
public class TCPListenerExample
{
public static void Main()
{
// Create the server side connection and
// start listening for clients.
TcpListener tcpListener = new TcpListener(IPAddress.Any,11000);
tcpListener.Start();
Console.WriteLine("Waiting for a connection....");
// Accept the pending client connection.
using TcpClient tcpClient = tcpListener.AcceptTcpClient();
Console.WriteLine("Connection accepted.");
// Get the stream to write the message
// that will be sent to the client.
using NetworkStream networkStream = tcpClient.GetStream();
string responseString = "Hello.";
// Set the write timeout to 10 millseconds.
networkStream.WriteTimeout = 10;
// Convert the message to a byte array and sent it to the client.
Byte[] sendBytes = Encoding.UTF8.GetBytes(responseString);
networkStream.Write(sendBytes, 0, sendBytes.Length);
Console.WriteLine("Message Sent.");
// Close the connection to the client.
tcpClient.Close();
// Stop listening for incoming connections
// and close the server.
tcpListener.Stop();
}
}
}
注解
如果写入操作未在此属性指定的时间内完成,则写入操作将 IOException引发 。
注意
此属性仅影响通过调用 Write 方法执行的同步写入操作。 此属性不会影响通过调用 BeginWrite 或 WriteAsync 方法执行的异步写入。