extends System.Object
extends System.IDisposable
| Variables: |
|---|
public System.Net.Sockets.AddressFamily AddressFamily |
public System.Int32 Available |
public System.Boolean Blocking |
public System.Boolean Connected |
public System.IntPtr Handle |
public System.Net.EndPoint LocalEndPoint |
public System.Net.Sockets.ProtocolType ProtocolType |
public System.Net.EndPoint RemoteEndPoint |
public System.Net.Sockets.SocketType SocketType |
| Constructors: |
|---|
public System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily addressFamily, System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType) Constructs and initializes a new instance of the System.Net.Sockets.Socket class. Parameter addressFamily: One of the values defined in the System.Net.Sockets.AddressFamily enumeration. Parameter socketType: One of the values defined in the System.Net.Sockets.SocketType enumeration. Parameter protocolType: One of the values defined in the System.Net.Sockets.ProtocolType enumeration. Throws: : The combination of addressFamily, socketType, and protocolType is invalid. -or- An error occurred while creating the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. The addressFamily parameter specifies the addressing scheme used by the current instance, the socketType parameter specifies the socket type of the current instance, and the protocolType parameter specifies the protocol used by the current instance. The three parameters are not independent. Some address families restrict which protocols are used, and often the socket type is determined by the protocol. When the specified values are not a valid combination, a System.Net.Sockets.SocketException exception is thrown. Using the Unknown member of either the System.Net.Sockets.AddressFamily or System.Net.Sockets.ProtocolType enumeration, results in a System.Net.Sockets.SocketException exception being thrown. |
| Functions: |
|---|
public System.Net.Sockets.Socket Accept() Creates and initializes a new System.Net.Sockets.Socket instance and connects it to an incoming connection request. Returns: A new connected System.Net.Sockets.Socket instance. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : An error occurred while accessing the socket. The System.Net.Sockets.Socket.Blocking property is set to false. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. This method is used only on the server-side of connection-oriented protocols. It extracts the first connection request from the queue of pending requests, creates a new System.Net.Sockets.Socket instance, and connects this instance to the socket associated with the request. The System.Net.Sockets.Socket.Blocking property of the socket determines the behavior of this method when there are no pending connection requests. When false, this method will throw a System.Net.Sockets.SocketException. When true, this method blocks. The following properties of the new System.Net.Sockets.Socket instance returned by this method have values identical to the corresponding properties of the current instance: The System.Net.Sockets.Socket.RemoteEndPoint property of the new instance is set to the local endpoint of the first request in the input queue. The System.Net.Sockets.Socket.Connected property is set to true. |
public System.IAsyncResult BeginAccept(System.AsyncCallback callback, System.Object state) Begins an asynchronous operation to accept an incoming connection request. Parameter callback: A System.AsyncCallback delegate, or null. Parameter state: An application-defined object, or null. Returns: A System.IAsyncResult instance that contains information about the asynchronous operation. Throws: : An error occurred while starting the operation. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. To retrieve the results of the operation and release resources allocated by the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method, and specify the System.IAsyncResult object returned by this method. The System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. If the callback parameter is not null, the method referenced by callback is invoked when the asynchronous operation completes. The System.IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method. The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method. To determine the connection status, check the System.Net.Sockets.Socket.Connected property, or use either the System.Net.Sockets.Socket.Poll(System.Int32,System.Net.Sockets.SelectMode) or System.Net.Sockets.Socket.Select(System.Collections.IList,System.Collections.IList,System.Collections.IList,System.Int32) method. For more information, see System.Net.Sockets.Socket.Accept, the synchronous version of this method. Example: The following excerpt from the System.Net.Sockets.Socket class overview example outlines an asynchronous accept operation. public class Server
{
static void Main()
{
.
.
.
listenSocket.BeginAccept(
new AsyncCallback(Server.acceptCallback),
listenSocket);
.
.
.
// EndAccept can be called here
.
.
.
}
public static void
acceptCallback(IAsyncResult asyncAccept)
{
Socket listenSocket =
(Socket)asyncAccept.AsyncState;
Socket serverSocket =
listenSocket.EndAccept(asyncAccept);
serverSocket.BeginReceive(...);
.
.
.
}
}
|
public System.IAsyncResult BeginConnect(System.Net.EndPoint remoteEP, System.AsyncCallback callback, System.Object state) Begins an asynchronous operation to associate the current instance with a remote endpoint. Parameter remoteEP: The System.Net.EndPoint associated with the socket to connect to. Parameter callback: A System.AsyncCallback delegate, or null. Parameter state: An application-defined object, or null. Returns: A System.IAsyncResult instance that contains information about the asynchronous operation. Throws: : remoteEP is null. Throws: : An error occurred while starting the operation. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. Throws: : A caller higher in the call stack does not have permission for the requested operation. To release resources allocated by the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method, and specify the System.IAsyncResult object returned by this method. The System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method. If the callback parameter is not null, the method referenced by callback is invoked when the asynchronous operation completes. The System.IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method. The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method. To determine the connection status, check the System.Net.Sockets.Socket.Connected property, or use either the System.Net.Sockets.Socket.Poll(System.Int32,System.Net.Sockets.SelectMode) or System.Net.Sockets.Socket.Select(System.Collections.IList,System.Collections.IList,System.Collections.IList,System.Int32) method. For more information, see System.Net.Sockets.Socket.Connect(System.Net.EndPoint), the synchronous version of this method. Example: For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method, see the System.Net.Sockets.Socket class overview. |
public System.IAsyncResult BeginReceive(System.Byte[] buffer, System.Int32 offset, System.Int32 size, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback callback, System.Object state) Begins an asynchronous operation to receive data from a socket. Parameter buffer: A System.Byte array to store data received from the socket. Parameter offset: A System.Int32 containing the zero-based position in buffer to begin storing the received data. Parameter size: A System.Int32 containing the number of bytes to receive. Parameter socketFlags: A bitwise combination of any of the following values defined in the System.Net.Sockets.SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek. Parameter callback: A System.AsyncCallback delegate, or null. Parameter state: An application-defined object, or null. Returns: A System.IAsyncResult instance that contains information about the asynchronous operation. Throws: : buffer is null. Throws: : offset < 0. -or- offset > buffer.Length. -or- size < 0. -or- size > buffer.Length - offset. Throws: : socketFlags is not a valid combination of values. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. To retrieve the results of the operation and release resources allocated by the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method, and specify the System.IAsyncResult object returned by this method. The System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method. If the callback parameter is not null, the method referenced by callback is invoked when the asynchronous operation completes. The System.IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method. The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method. For more information, see System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags), the synchronous version of this method. Example: For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, see the System.Net.Sockets.Socket class overview. |
public System.IAsyncResult BeginReceiveFrom(System.Byte[] buffer, System.Int32 offset, System.Int32 size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint& remoteEP, System.AsyncCallback callback, System.Object state) Begins an asynchronous operation to receive data from a socket and, for connectionless protocols, store the endpoint associated with the socket that sent the data. Parameter buffer: A System.Byte array to store data received from the socket. Parameter offset: A System.Int32 containing the zero-based position in buffer to begin storing the received data. Parameter size: A System.Int32 containing the number of bytes to receive. Parameter socketFlags: A bitwise combination of any of the following values defined in the System.Net.Sockets.SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek . Parameter remoteEP: An instance of a class derived from the System.Net.EndPoint class, which contains the endpoint associated with the socket that sent the data. Parameter callback: A System.AsyncCallback delegate, or null. Parameter state: An application-defined object, or null. Returns: A System.IAsyncResult instance that contains information about the asynchronous operation. Throws: : buffer is null. -or- remoteEP is null. Throws: : offset < 0. -or- offset > buffer.Length. -or- size < 0. -or- size > buffer.Length - offset. Throws: : socketFlags is not a valid combination of values. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. Throws: : A caller in the call stack does not have the required permissions. To retrieve the results of the operation and release resources allocated by the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) method, and specify the System.IAsyncResult object returned by this method. The System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method. If the callback parameter is not null, the method referenced by callback is invoked when the asynchronous operation completes. The System.IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) method. The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method. For more information, see System.Net.Sockets.Socket.ReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@), the synchronous version of this method. Example: For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, see System.Net.Sockets.Socket. |
public System.IAsyncResult BeginSend(System.Byte[] buffer, System.Int32 offset, System.Int32 size, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback callback, System.Object state) Begins an asynchronous operation to send data to a connected socket. Parameter buffer: A System.Byte array storing data to send to the socket. Parameter offset: A System.Int32 containing the zero-based position in buffer containing the starting location of the data to send. Parameter size: A System.Int32 containing the number of bytes to send. Parameter socketFlags: A bitwise combination of any of the following values defined in the System.Net.Sockets.SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand . Parameter callback: A System.AsyncCallback delegate, or null. Parameter state: An application-defined object, or null. Returns: A System.IAsyncResult instance that contains information about the asynchronous operation. Throws: : buffer is null. Throws: : offset < 0. -or- offset > buffer.Length. -or- size < 0. -or- size > buffer.Length - offset. Throws: : socketFlags is not a valid combination of values. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. To retrieve the results of the operation and release resources allocated by the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method, and specify the System.IAsyncResult object returned by this method. The System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method. If the callback parameter is not null, the method referenced by callback is invoked when the asynchronous operation completes. The System.IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method. The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method. For more information, see System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags), the synchronous version of this method. Example: For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, see the System.Net.Sockets.Socket class overview. |
public System.IAsyncResult BeginSendTo(System.Byte[] buffer, System.Int32 offset, System.Int32 size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP, System.AsyncCallback callback, System.Object state) Begins an asynchronous operation to send data to the socket associated with the specified endpoint. Parameter buffer: A System.Byte array storing data to send to the socket. Parameter offset: A System.Int32 containing the zero-based position in buffer to begin sending data. Parameter size: A System.Int32 containing the number of bytes to send. Parameter socketFlags: A bitwise combination of any of the following values defined in the System.Net.Sockets.SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand . Parameter remoteEP: The System.Net.EndPoint associated with the socket to receive the data. Parameter callback: A System.AsyncCallback delegate, or null. Parameter state: An application-defined object, or null. Returns: A System.IAsyncResult instance that contains information about the asynchronous operation. Throws: : buffer is null. -or- remoteEP is null. Throws: : offset < 0. -or- offset > buffer.Length. -or- size < 0. -or- size > buffer.Length - offset. Throws: : socketFlags is not a valid combination of values. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. Throws: : A caller in the call stack does not have the required permissions. To retrieve the results of the operation and release resources allocated by the System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) method, and specify the System.IAsyncResult object returned by this method. The System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) method. If the callback parameter is not null, the method referenced by callback is invoked when the asynchronous operation completes. The System.IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) method. The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method. For more information, see System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint), the synchronous version of this method. Example: For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, see the System.Net.Sockets.Socket class overview. |
public System.Void Bind(System.Net.EndPoint localEP) Associates the current instance with a local endpoint. Parameter localEP: The local System.Net.EndPoint to be associated with the socket. Throws: : localEP is null. Throws: : An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. Throws: : A caller in the call stack does not have the required permission. This method sets the System.Net.Sockets.Socket.LocalEndPoint property of the current instance to localEP. For connection-oriented protocols, this method is generally used only on the server-side and is required to be called before the first call to the System.Net.Sockets.Socket.Listen(System.Int32) method. On the client-side, binding is usually performed implicitly by the System.Net.Sockets.Socket.Connect(System.Net.EndPoint) method. For connectionless protocols, the System.Net.Sockets.Socket.Connect(System.Net.EndPoint) System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint), and System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) methods bind the current instance to the local endpoint if the current instance has not previously been bound. |
public System.Void Close() Closes the current instance and releases all managed and unmanaged resources allocated by the current instance. This method calls the System.Net.Sockets.Socket.Dispose(System.Boolean)(System.Boolean) method with the argument set to true, which frees both managed and unmanaged resources used by the current instance. The socket attempts to perform a graceful closure when the System.Net.Sockets.SocketOptionName.Linger socket option is enabled and set to a non-zero linger time. In all other cases, closure is forced and any pending data is lost. |
public System.Void Connect(System.Net.EndPoint remoteEP) Associates the current instance with a remote endpoint. Parameter remoteEP: The System.Net.EndPoint associated with the socket to connect to. Throws: : remoteEP is null. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. Throws: : A caller in the call stack does not have the required permission. This method sets the System.Net.Sockets.Socket.RemoteEndPoint property of the current instance to remoteEP. For connection-oriented protocols, this method establishes a connection between the current instance and the socket associated with remoteEP. This method is used only on the client-side. The System.Net.Sockets.Socket.Accept method establishes the connection on the server-side. Once the connection has been made, data can be sent using the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method, and received using the System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method. For connectionless protocols, the System.Net.Sockets.Socket.Connect(System.Net.EndPoint) method can be used from both client and server-sides, allowing the use of the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method instead of the System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint) method. The System.Net.Sockets.Socket.RemoteEndPoint property is set to remoteEP and the System.Net.Sockets.Socket.LocalEndPoint property is set to a value determined by the protocol; however, a connection is not established. Subsequent data is required to be received on the endpoint set in the System.Net.Sockets.Socket.LocalEndPoint property. |
protected virtual System.Void Dispose(System.Boolean disposing) Closes the current instance, releases the unmanaged resources allocated by the current instance, and optionally releases the managed resources. Parameter disposing: A System.Boolean. Specify true to release both managed and unmanaged resources; false to release only unmanaged resources. This method closes the current System.Net.Sockets.Socket instance and releases all unmanaged resources allocated by the current instance. When disposing is true, this method also releases all resources held by any managed objects allocated by the current instance. This method closes the current System.Net.Sockets.Socket instance but does not release any managed resources. The System.Net.Sockets.Socket.Dispose(System.Boolean) method can be called multiple times by other objects. When overriding this method, do not reference objects that have been previously disposed in an earlier call. Use this method to release resources allocated by the current instance. |
public System.Net.Sockets.Socket EndAccept(System.IAsyncResult asyncResult) Ends an asynchronous call to accept an incoming connection request. Parameter asyncResult: A System.IAsyncResult object that holds the state information for the asynchronous operation. Returns: A new connected System.Net.Sockets.Socket instance. Throws: : asyncResult is null. Throws: : asyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. Throws: : System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) was previously called for this operation. Throws: : An error occurred during the operation. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. This method blocks if the asynchronous operation has not completed. The System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method call that began the request. If the System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method is invoked via the System.AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method, the asyncResult parameter is the System.IAsyncResult argument passed to the delegate's method. Example: For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method, see the System.Net.Sockets.Socket class overview. |
public System.Void EndConnect(System.IAsyncResult asyncResult) Ends an asynchronous call to associate the current instance with a remote endpoint. Parameter asyncResult: A System.IAsyncResult object that holds the state information for the asynchronous operation. Throws: : asyncResult is null. Throws: : asyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method. Throws: : System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) was previously called for this operation. Throws: : An error occurred during the operation. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. This method blocks if the asynchronous operation has not completed. The System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method call that began the request. If the System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method is invoked via the System.AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method, the asyncResult parameter is the System.IAsyncResult argument passed to the delegate's method. Example: For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method, see the System.Net.Sockets.Socket class overview. |
public System.Int32 EndReceive(System.IAsyncResult asyncResult) Ends an asynchronous call to receive data from a socket. Parameter asyncResult: A System.IAsyncResult object that holds the state information for the asynchronous operation. Returns: A System.Int32 containing the number of bytes received. Throws: : asyncResult is null. Throws: : asyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method. Throws: : System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) was previously called for this operation. Throws: : An error occurred during the operation. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. This method blocks if the asynchronous operation has not completed. The System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method call that began the request. If the System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method is invoked via the System.AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, the asyncResult parameter is the System.IAsyncResult argument passed to the delegate's method. Example: For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method, see the System.Net.Sockets.Socket class overview. |
public System.Int32 EndReceiveFrom(System.IAsyncResult asyncResult, System.Net.EndPoint& endPoint) Ends an asynchronous call to receive data from a socket and store the endpoint associated with the socket that sent the data. Parameter asyncResult: A System.IAsyncResult object that holds the state information for the asynchronous operation. Parameter endPoint: A reference to the System.Net.EndPoint associated with the socket that sent the data. Returns: A System.Int32 containing the number of bytes received. Throws: : asyncResult is null. Throws: : asyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method. Throws: : System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) was previously called for this operation. Throws: : An error occurred during the operation. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. This method blocks if the asynchronous operation has not completed. The System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method call that began the request. If the System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) method is invoked via the System.AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method, the asyncResult parameter is the System.IAsyncResult argument passed to the delegate's method. Example: For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, see the System.Net.Sockets.Socket class overview. |
public System.Int32 EndSend(System.IAsyncResult asyncResult) Ends an asynchronous call to send data to a connected socket. Parameter asyncResult: A System.IAsyncResult object that holds the state information for the asynchronous operation. Returns: A System.Int32 containing the number of bytes sent. Throws: : asyncResult is null. Throws: : asyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method. Throws: : System.Net.Sockets.Socket.EndSend(System.IAsyncResult) was previously called for this operation. Throws: : An error occurred during the operation. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. This method blocks if the asynchronous operation has not completed. The System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method call that began the request. If the System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method is invoked via the System.AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, the asyncResult parameter is the System.IAsyncResult argument passed to the delegate's method. Example: For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method, see the System.Net.Sockets.Socket class overview. |
public System.Int32 EndSendTo(System.IAsyncResult asyncResult) Ends an asynchronous call to send data to a socket associated with a specified endpoint. Parameter asyncResult: A System.IAsyncResult object that holds the state information for the asynchronous operation. Returns: A System.Int32 containing the number of bytes sent. Throws: : asyncResult is null. Throws: : asyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint) method. Throws: : System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) was previously called for this operation. Throws: : An error occurred during the operation. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. This method blocks if the asynchronous operation has not completed. The System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) method call that began the request. If the System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) method is invoked via the System.AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) method, the asyncResult parameter is the System.IAsyncResult argument passed to the delegate's method. Example: For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, see the System.Net.Sockets.Socket class overview. |
public System.Void Finalize() Closes the current instance and releases unmanaged resources allocated by the current instance. Application code does not call this method; it is automatically invoked during garbage collection unless finalization by the garbage collector has been disabled. For more information, see System.GC.SuppressFinalize(System.Object), and System.Object.Finalize. This method calls System.Net.Sockets.NetworkStream.Dispose(System.Boolean)(false) to free unmanaged resources used by the current instance. This method overrides System.Object.Finalize. |
public System.Int32 GetHashCode() Generates a hash code for the current instance. Returns: A System.Int32 containing the hash code for the current instance. The algorithm used to generate the hash code is unspecified. This method overrides System.Object.GetHashCode. |
public System.Object GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName) Retrieves an object containing the value of the specified socket option. Parameter optionLevel: One of the values defined in the System.Net.Sockets.SocketOptionLevel enumeration. Parameter optionName: One of the values defined in the System.Net.Sockets.SocketOptionName enumeration. Returns: The following table describes the values returned by this method. Throws: : An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. Socket options determine the behavior of the current instance. optionLevel and optionName are not independent. See the System.Net.Sockets.Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,System.Int32)(SocketOptionLevel, SocketOptionName, Int32) method for a listing of the values of the System.Net.Sockets.SocketOptionName enumeration grouped by System.Net.Sockets.SocketOptionLevel. Example: The following example gets the state of the linger option and the size of the receive buffer, changes the values of both, then gets the new values. using System;
using System.Net.Sockets;
class OptionTest{
public static void Main() {
// Get the current option values.
Socket someSocket =
new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
LingerOption lingerOp =
(LingerOption)someSocket.GetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.Linger);
int receiveBuffer =
(int)someSocket.GetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.ReceiveBuffer);
Console.WriteLine(
"Linger option is {0} and set to {1} seconds.",
lingerOp.Enabled.ToString(),
lingerOp.LingerTime.ToString() );
Console.WriteLine(
"Size of the receive buffer is {0} bytes.",
receiveBuffer.ToString() );
// Change the options.
lingerOp = new LingerOption(true, 10);
someSocket.SetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.Linger,
lingerOp);
someSocket.SetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.ReceiveBuffer,
2048);
Console.WriteLine(
"The SetSocketOption method has been called.");
// Get the new option values.
lingerOp =
(LingerOption)someSocket.GetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.Linger);
receiveBuffer =
(int)someSocket.GetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.ReceiveBuffer);
Console.WriteLine(
"Linger option is now {0} and set to {1} seconds.",
lingerOp.Enabled.ToString(),
lingerOp.LingerTime.ToString());
Console.WriteLine(
"Size of the receive buffer is now {0} bytes.",
receiveBuffer.ToString());
}
}
The output is Linger option is False and set to 0 seconds. Size of the receive buffer is 8192 bytes. The SetSocketOption method has been called. Linger option is now True and set to 10 seconds. Size of the receive buffer is now 2048 bytes. |
public System.Void GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, System.Byte[] optionValue) Retrieves the value of the specified socket option. Parameter optionLevel: One of the values defined in the System.Net.Sockets.SocketOptionLevel enumeration. Parameter optionName: One of the values defined in the System.Net.Sockets.SocketOptionName enumeration. Parameter optionValue: A System.Byte array that receives the value of the specified socket option. Throws: : optionValue is too small to store the value of the specified socket option. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. Socket options determine the behavior of the current instance. Upon successful completion, the array specified by the optionValue parameter contains the value of the specified socket option. When the length of the optionValue array is smaller than the number of bytes required to store the value of the specified socket option, a System.Net.Sockets.SocketException exception is thrown. |
public System.Byte[] GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, System.Int32 optionLength) Retrieves the value of the specified socket option. Parameter optionLevel: One of the values defined in the System.Net.Sockets.SocketOptionLevel enumeration. Parameter optionName: One of the values defined in the System.Net.Sockets.SocketOptionName enumeration. Parameter optionLength: A System.Int32 containing the maximum length, in bytes, of the value of the specified socket option. Returns: A System.Byte array containing the value of the specified socket option. Throws: : optionLength is smaller than the number of bytes required to store the value of the specified socket option. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. Socket options determine the behavior of the current instance. The optionLength parameter is used to allocate an array to store the value of the specified option. When this value is smaller than the number of bytes required to store the value of the specified option, a System.Net.Sockets.SocketException exception is thrown. When this value is greater than or equal to the number of bytes required to store the value of the specified option, the array returned by this method is allocated to be exactly the required length. |
public System.Int32 IOControl(System.Int32 ioControlCode, System.Byte[] optionInValue, System.Byte[] optionOutValue) Provides low-level access to the socket, the transport protocol, or the communications subsystem. Parameter ioControlCode: A System.Int32 containing the control code of the operation to perform. Parameter optionInValue: A System.Byte array containing the input data required by the operation. Parameter optionOutValue: A System.Byte array containing the output data supplied by the operation. Returns: A System.Int32 containing the length of the optionOutValue array after the method returns. Throws: : An attempt was made to change the blocking mode. Use the System.Net.Sockets.Socket.Blocking property to change the blocking mode. Throws: : An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. If an attempt is made to change the blocking mode of the current instance, an exception is thrown. Use the System.Net.Sockets.Socket.Blocking property to change the blocking mode. The control codes and their requirements are implementation defined. Do not use this method if platform independence is a requirement. Input data is not required for all control codes. Output data is not supplied by all control codes and, if not supplied, the return value is 0. Example: The following example gets the number of bytes of available data to be read and writes the result to the console on a Windows system. The remote endpoint (remoteEndpoint) to connect to may need to be changed to a value that is valid on the current system. using System;
using System.Net;
using System.Net.Sockets;
class App {
static void Main() {
IPAddress remoteAddress =
Dns.Resolve(Dns.GetHostName()).AddressList[0];
IPEndPoint remoteEndpoint =
new IPEndPoint(remoteAddress, 80);
Socket someSocket =
new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
someSocket.Connect(remoteEndpoint);
int fionRead = 0x4004667F;
byte[]inValue = {0x00, 0x00, 0x00, 0x00};
byte[]outValue = {0x00, 0x00, 0x00, 0x00};
someSocket.IOControl(fionRead, inValue, outValue);
uint bytesAvail = BitConverter.ToUInt32(outValue, 0);
Console.WriteLine(
"There are {0} bytes available to be read.",
bytesAvail.ToString() );
}
}
The output is There are 0 bytes available to be read. |
public System.Void Listen(System.Int32 backlog) Places the current instance into the listening state where it waits for incoming connection requests. Parameter backlog: A System.Int32 containing the maximum length of the queue of pending connections. Throws: : The System.Net.Sockets.Socket.Connected property of the current instance is true, or an error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. Once this method is called, incoming connection requests are placed in a queue. The maximum size of the queue is specified by the backlog parameter. The size of the queue is limited to legal values by the underlying protocol. Illegal values of the backlog parameter are replaced with a legal value, which is implementation defined. If a connection request arrives and the queue is full, a System.Net.Sockets.SocketException is thrown on the client. A socket in the listening state has no remote endpoint associated with it. Attempting to access the System.Net.Sockets.Socket.RemoteEndPoint property throws a System.Net.Sockets.SocketException exception. This method is ignored if called more than once on the current instance. This method is used only on the server-side of connection-oriented protocols. Call the System.Net.Sockets.Socket.Bind(System.Net.EndPoint) method before this method is called the first time. Call the System.Net.Sockets.Socket.Listen(System.Int32) method before the first call to the System.Net.Sockets.Socket.Accept method. |
public System.Boolean Poll(System.Int32 microSeconds, System.Net.Sockets.SelectMode mode) Determines the read, write, or error status of the current instance. Parameter microSeconds: A System.Int32 containing the time to wait for a response, in microseconds. Set the microSeconds parameter to a negative value to wait indefinitely for a response. Parameter mode: One of the values defined in the System.Net.Sockets.SelectMode enumeration. Returns: A System.Boolean where true indicates the current instance satisfies at least one of the conditions in the following table corresponding to the specified System.Net.Sockets.SelectMode value; otherwise, false. false is returned if the status of the current instance cannot be determined within the time specified by microSeconds . Throws: : mode is not one of the values defined in the System.Net.Sockets.SelectMode enumeration. Throws: : An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. |
public System.Int32 Receive(System.Byte[] buffer, System.Int32 size, System.Net.Sockets.SocketFlags socketFlags) Receives data from a socket. Parameter buffer: A System.Byte array to store data received from the socket. Parameter size: A System.Int32 containing the number of bytes to receive. Parameter socketFlags: A bitwise combination of any of the following values defined in the System.Net.Sockets.SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek. Returns: A System.Int32 containing the number of bytes received. Throws: : buffer is null. Throws: : size < 0. -or- size > buffer.Length. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : socketFlags is not a valid combination of values. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : A caller in the call stack does not have the required permissions. Throws: : The current instance has been disposed. This method is equivalent to System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, size, socketFlags). |
public System.Int32 Receive(System.Byte[] buffer, System.Net.Sockets.SocketFlags socketFlags) Receives data from a socket. Parameter buffer: A System.Byte array to store data received from the socket. Parameter socketFlags: A bitwise combination of any of the following values defined in the System.Net.Sockets.SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek. Returns: A System.Int32 containing the number of bytes received. Throws: : buffer is null. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : socketFlags is not a valid combination of values. Throws: : A caller in the call stack does not have the required permissions. Throws: : The current instance has been disposed. This method is equivalent to System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, buffer.Length, socketFlags). |
public System.Int32 Receive(System.Byte[] buffer, System.Int32 offset, System.Int32 size, System.Net.Sockets.SocketFlags socketFlags) Receives data from a socket. Parameter buffer: A System.Byte array to store data received from the socket. Parameter offset: A System.Int32 containing the zero-based position in buffer to begin storing the received data. Parameter size: A System.Int32 containing the number of bytes to receive. Parameter socketFlags: A bitwise combination of any of the following values defined in the System.Net.Sockets.SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek. Returns: A System.Int32 containing the number of bytes received. Throws: : buffer is null. Throws: : offset < 0. -or- offset > buffer.Length. -or- size < 0. -or- size > buffer.Length - offset. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : socketFlags is not a valid combination of values. -or- The System.Net.Sockets.Socket.LocalEndPoint property was not set. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : A caller in the call stack does not have the required permissions. Throws: : The current instance has been disposed. The System.Net.Sockets.Socket.LocalEndPoint property is required to be set before this method is called. The System.Net.Sockets.Socket.Blocking property of the socket determines the behavior of this method when no incoming data is available. When false, the System.Net.Sockets.SocketException exception is thrown. When true, this method blocks and waits for data to arrive. For System.Net.Sockets.SocketType.Stream socket types, if the remote socket was shut down gracefully, and all data was received, this method immediately returns zero, regardless of the blocking state. For message-oriented sockets, if the message is larger than the size of buffer, the buffer is filled with the first part of the message, and the System.Net.Sockets.SocketException exception is thrown. For unreliable protocols, the excess data is lost; for reliable protocols, the data is retained by the service provider. When the System.Net.Sockets.SocketFlags.OutOfBand flag is specified as part of the socketFlags parameter and the socket is configured for in-line reception of out-of-band (OOB) data (using the System.Net.Sockets.SocketOptionName.OutOfBandInline socket option) and OOB data is available, only OOB data is returned. When the System.Net.Sockets.SocketFlags.Peek flag is specified as part of the socketFlags parameter, available data is copied into buffer but is not removed from the system buffer. |
public System.Int32 Receive(System.Byte[] buffer) Receives data from a socket. Parameter buffer: A System.Byte array to store data received from the socket. Returns: A System.Int32 containing the number of bytes received. Throws: : buffer is null. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : A caller in the call stack does not have the required permissions. Throws: : The current instance has been disposed. This method is equivalent to System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None). |
public System.Int32 ReceiveFrom(System.Byte[] buffer, System.Net.EndPoint& remoteEP) Receives data from a socket and, for connectionless protocols, stores the endpoint associated with the socket that sent the data. Parameter buffer: A System.Byte array to store data received from the socket. Parameter remoteEP: A reference to the System.Net.EndPoint associated with the socket that sent the data. Returns: A System.Int32 containing the number of bytes received. Throws: : buffer or remoteEP is null. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. This method is equivalent to System.Net.Sockets.Socket.ReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@)(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, remoteEP). |
public System.Int32 ReceiveFrom(System.Byte[] buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint& remoteEP) Receives data from a socket and, for connectionless protocols, stores the endpoint associated with the socket that sent the data. Parameter buffer: A System.Byte array to store data received from the socket. Parameter socketFlags: A bitwise combination of any of the following values defined in the System.Net.Sockets.SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek. Parameter remoteEP: A reference to the System.Net.EndPoint associated with the socket that sent the data. Returns: A System.Int32 containing the number of bytes received. Throws: : buffer or remoteEP is null. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : socketFlags specified an invalid value. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : A caller in the call stack does not have the required permissions. Throws: : The current instance has been disposed. This method is equivalent to System.Net.Sockets.Socket.ReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@)(buffer, 0, buffer.Length, socketFlags, remoteEP). |
public System.Int32 ReceiveFrom(System.Byte[] buffer, System.Int32 size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint& remoteEP) Receives data from a socket and, for connectionless protocols, stores the endpoint associated with the socket that sent the data. Parameter buffer: A System.Byte array to store data received from the socket. Parameter size: A System.Int32 containing the number of bytes to receive. Parameter socketFlags: A bitwise combination of any of the following values defined in the System.Net.Sockets.SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek. Parameter remoteEP: A reference to the System.Net.EndPoint associated with the socket that sent the data. Returns: A System.Int32 containing the number of bytes received. Throws: : buffer or remoteEP is null. Throws: : size < 0. -or- size > buffer.Length. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : socketFlags is not a valid combination of values. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : A caller in the call stack does not have the required permissions. Throws: : The current instance has been disposed. This method is equivalent to System.Net.Sockets.Socket.ReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@)(buffer, 0, size , socketFlags, remoteEP ). |
public System.Int32 ReceiveFrom(System.Byte[] buffer, System.Int32 offset, System.Int32 size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint& remoteEP) Receives data from a socket and, for connectionless protocols, stores the endpoint associated with the socket that sent the data. Parameter buffer: A System.Byte array to store data received from the socket. Parameter offset: A System.Int32 containing the zero-based position in buffer to begin storing the received data. Parameter size: A System.Int32 containing the number of bytes to receive. Parameter socketFlags: A bitwise combination of any of the following values defined in the System.Net.Sockets.SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek. Parameter remoteEP: A reference to the System.Net.EndPoint associated with the socket that sent the data. Returns: A System.Int32 containing the number of bytes received. Throws: : buffer or remoteEP is null. Throws: : offset < 0. -or- offset > buffer.Length. -or- size < 0. -or- size > buffer.Length - offset. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : socketFlags is not a valid combination of values. -or- The System.Net.Sockets.Socket.LocalEndPoint property was not set. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : A caller in the call stack does not have the required permissions. Throws: : The current instance has been disposed. For connectionless protocols, when this method successfully completes, remoteEP contains the endpoint associated with the socket that sent the data. For connection-oriented protocols, remoteEP is left unchanged. The System.Net.Sockets.Socket.LocalEndPoint property is required to be set before this method is called or a System.Net.Sockets.SocketException is thrown. The System.Net.Sockets.Socket.Blocking property of the socket determines the behavior of this method when no incoming data is available. When false, the System.Net.Sockets.SocketException exception is thrown. When true, this method blocks and waits for data to arrive. For System.Net.Sockets.SocketType.Stream socket types, if the remote socket was shut down gracefully, and all data was received, this method immediately returns zero, regardless of the blocking state. For message-oriented sockets, if the message is larger than the size of buffer, the buffer is filled with the first part of the message, and the System.Net.Sockets.SocketException exception is thrown. For unreliable protocols, the excess data is lost; for reliable protocols, the data is retained by the service provider. When the System.Net.Sockets.SocketFlags.OutOfBand flag is specified as part of thesocketFlags parameter and the socket is configured for in-line reception of out-of-band (OOB) data (using the System.Net.Sockets.SocketOptionName.OutOfBandInline socket option) and OOB data is available, only OOB data is returned. When the System.Net.Sockets.SocketFlags.Peek flag is specified as part of the socketFlags parameter, available data is copied into buffer but is not removed from the system buffer. |
public static System.Void Select(System.Collections.IList checkRead, System.Collections.IList checkWrite, System.Collections.IList checkError, System.Int32 microSeconds) Determines the read, write, or error status of a set of System.Net.Sockets.Socket instances. Parameter checkRead: A System.Collections.IList object containing the System.Net.Sockets.Socket instances to check for read status. Parameter checkWrite: A System.Collections.IList object containing the System.Net.Sockets.Socket instances to check for write status. Parameter checkError: A System.Collections.IList object containing the System.Net.Sockets.Socket instances to check for error status. Parameter microSeconds: A System.Int32 that specifies the time to wait for a response, in microseconds. Specify a negative value to wait indefinitely for the status to be determined. Throws: : All of the following parameters are null or empty: checkRead, checkWrite, and checkError. Throws: : An error occurred while accessing one of the sockets. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Upon successful completion, this method removes all System.Net.Sockets.Socket instances from the specified list that do not satisfy one of the conditions associated with that list. The following table describes the conditions for each list. To determine the status of a specific System.Net.Sockets.Socket instance, check whether the instance remains in the list after the method returns. When the method cannot determine the status of all the System.Net.Sockets.Socket instances within the time specified in the microseconds parameter, the method removes all the System.Net.Sockets.Socket instances from all the lists and returns. At least one of checkRead, checkWrite, or checkError, is required to contain at least one System.Net.Sockets.Socket instance. The other parameters can be empty or null. Example: The following example determines the status of the socket instance named socket3 and writes the result to the console. using System;
using System.Collections;
using System.Net.Sockets;
class SelectTest {
public static void Main() {
Socket socket1 =
new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
Socket socket2 =
new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
Socket socket3 =
new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
ArrayList readList = new ArrayList();
ArrayList writeList = new ArrayList();
ArrayList errorList = new ArrayList();
readList.Add(socket1);
readList.Add(socket2);
readList.Add(socket3);
errorList.Add(socket1);
errorList.Add(socket3);
// readList.Contains(Socket3) returns true
// if Socket3 is in ReadList.
Console.WriteLine(
"socket3 is placed in readList and errorList.");
Console.WriteLine(
"socket3 is {0}in readList.",
readList.Contains(socket3) ? "" : "not " );
Console.WriteLine(
"socket3 is {0}in writeList.",
writeList.Contains(socket3) ? "" : "not " );
Console.WriteLine(
"socket3 is {0}in errorList.",
errorList.Contains(socket3) ? "" : "not " );
Socket.Select(readList, writeList, errorList, 10);
Console.WriteLine("The Select method has been called.");
Console.WriteLine(
"socket3 is {0}in readList.",
readList.Contains(socket3) ? "" : "not " );
Console.WriteLine(
"socket3 is {0}in writeList.",
writeList.Contains(socket3) ? "" : "not " );
Console.WriteLine(
"socket3 is {0}in errorList.",
errorList.Contains(socket3) ? "" : "not " );
}
}
The output is socket3 is placed in readList and errorList. socket3 is in readList. socket3 is not in writeList. socket3 is in errorList. The Select method has been called. socket3 is not in readList. socket3 is not in writeList. socket3 is not in errorList. |
public System.Int32 Send(System.Byte[] buffer, System.Int32 offset, System.Int32 size, System.Net.Sockets.SocketFlags socketFlags) Sends data to a connected socket. Parameter buffer: A System.Byte array containing data to send to the socket. Parameter offset: A System.Int32 that specifies the zero-based position in buffer that is the starting location of the data to send. Parameter size: A System.Int32 containing the number of bytes to send. Parameter socketFlags: A bitwise combination of any of the following values defined in the System.Net.Sockets.SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand. Returns: A System.Int32 containing the number of bytes sent. Throws: : buffer is null. Throws: : offset < 0. -or- offset > buffer.Length. -or- size < 0. -or- size > buffer.Length - offset. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : socketFlags is not a valid combination of values. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. For connection-oriented protocols, the System.Net.Sockets.Socket.LocalEndPoint property of the current instance is required to be set before calling this method. For connectionless protocols, calling the System.Net.Sockets.Socket.Connect(System.Net.EndPoint) methods sets the System.Net.Sockets.Socket.RemoteEndPoint property and allows the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method to be used instead of the System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint) method. When the System.Net.Sockets.SocketFlags.DontRoute flag is specified as part of the socketFlags parameter, the sent data is not routed. When the System.Net.Sockets.SocketFlags.OutOfBand flag is specified as part of the socketFlags parameter, only out-of-band (OOB) data is sent. When the System.Net.Sockets.Socket.Blocking property of the current instance is set to true and buffer space is not available within the underlying protocol, this method blocks. For message-oriented sockets, when size is greater than the maximum message size of the underlying protocol, no data is sent and the System.Net.Sockets.SocketException exception is thrown. |
public System.Int32 Send(System.Byte[] buffer) Sends data to a connected socket. Parameter buffer: A System.Byte array containing data to send to the socket. Returns: A System.Int32 containing the number of bytes sent. Throws: : buffer is null. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. This method is equivalent to System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None). |
public System.Int32 Send(System.Byte[] buffer, System.Net.Sockets.SocketFlags socketFlags) Sends data to a connected socket. Parameter buffer: A System.Byte array containing data to send to the socket. Parameter socketFlags: A bitwise combination of any of the following values defined in the System.Net.Sockets.SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand. Returns: A System.Int32 containing the number of bytes sent. Throws: : buffer is null. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : socketFlags is not a valid combination of values. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. This method is equivalent to System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, buffer.Length, socketFlags). |
public System.Int32 Send(System.Byte[] buffer, System.Int32 size, System.Net.Sockets.SocketFlags socketFlags) Sends data to a connected socket. Parameter buffer: A System.Byte array containing data to send to the socket. Parameter size: A System.Int32 containing the number of bytes to send. Parameter socketFlags: A bitwise combination of any of the following values defined in the System.Net.Sockets.SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand. Returns: A System.Int32 containing the number of bytes sent. Throws: : buffer is null. Throws: : size < 0. -or- size > buffer.Length. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : socketFlags is not a valid combination of values. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. This method is equivalent to System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, size, socketFlags). |
public System.Int32 SendTo(System.Byte[] buffer, System.Net.EndPoint remoteEP) Sends data to the socket associated with the specified endpoint. Parameter buffer: A System.Byte array containing data to send to the socket. Parameter remoteEP: The System.Net.EndPoint associated with the socket to receive the data. Returns: A System.Int32 containing the number of bytes sent. Throws: : buffer or remoteEP is null. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : A caller in the call stack does not have the required permissions. Throws: : The current instance has been disposed. This method is equivalent to System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint)(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, remoteEP). |
public System.Int32 SendTo(System.Byte[] buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) Sends data to the socket associated with the specified endpoint. Parameter buffer: A System.Byte array containing data to send to the socket. Parameter socketFlags: A bitwise combination of any of the following values defined in the System.Net.Sockets.SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand. Parameter remoteEP: The System.Net.EndPoint associated with the socket to receive the data. Returns: A System.Int32 containing the number of bytes sent. Throws: : buffer or remoteEP is null. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : socketFlags is not a valid combination of values. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : A caller in the call stack does not have the required permissions. Throws: : The current instance has been disposed. This method is equivalent to System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint)(buffer, 0, buffer.Length, socketFlags, remoteEP). |
public System.Int32 SendTo(System.Byte[] buffer, System.Int32 size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) Sends data to the socket associated with the specified endpoint. Parameter buffer: A System.Byte array containing data to send to the socket. Parameter size: A System.Int32 containing the number of bytes to send. Parameter socketFlags: A bitwise combination of any of the following values defined in the System.Net.Sockets.SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand. Parameter remoteEP: The System.Net.EndPoint associated with the socket to receive the data. Returns: A System.Int32 containing the number of bytes sent. Throws: : buffer or remoteEP is null. Throws: : size < 0. -or- size > buffer.Length. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : socketFlags is not a valid combination of values. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : A caller in the call stack does not have the required permissions. Throws: : The current instance has been disposed. This method is equivalent to System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint)(buffer, 0, size, socketFlags, remoteEP). |
public System.Int32 SendTo(System.Byte[] buffer, System.Int32 offset, System.Int32 size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) Sends data to the socket associated with the specified endpoint. Parameter buffer: A System.Byte array containing data to send to the socket. Parameter offset: A System.Int32 that specifies the zero-based position in buffer that is the starting location of the data to send. Parameter size: A System.Int32 containing the number of bytes to send. Parameter socketFlags: A bitwise combination of any of the following values defined in the System.Net.Sockets.SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand. Parameter remoteEP: The System.Net.EndPoint associated with the socket to receive the data. Returns: A System.Int32 containing the number of bytes sent. Throws: : buffer or remoteEP is null. Throws: : offset < 0. -or- offset > buffer.Length. -or- size < 0. -or- size > buffer.Length - offset. Throws: : An asynchronous call is pending and a blocking method has been called. Throws: : socketFlags is not a valid combination of values. -or- An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : A caller in the call stack does not have the required permissions. Throws: : The current instance has been disposed. For connected sockets using connectionless protocols, remoteEP overrides the endpoint specified in the System.Net.Sockets.Socket.RemoteEndPoint property. For unconnected sockets using connectionless protocols, this method sets the System.Net.Sockets.Socket.LocalEndPoint property of the current instance to a value determined by the protocol. Subsequent data is required to be received on LocalEndPoint. When the System.Net.Sockets.SocketFlags.DontRoute flag is specified as part of the socketFlags parameter, the sent data is not routed. When the System.Net.Sockets.SocketFlags.OutOfBand flag is specified as part of the socketFlags parameter, only out-of-band (OOB) data is sent. When the System.Net.Sockets.Socket.Blocking property of the current instance is set to true and buffer space is not available within the underlying protocol, this method blocks. For message-oriented sockets, when size is greater than the maximum message size of the underlying protocol, no data is sent and the System.Net.Sockets.SocketException exception is thrown. For connection-oriented sockets, the remoteEP parameter is ignored. |
public System.Void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, System.Object optionValue) Sets the System.Net.Sockets.SocketOptionName.AddMembership, System.Net.Sockets.SocketOptionName.DropMembership, or System.Net.Sockets.SocketOptionName.Linger socket options. Parameter optionLevel: Either the Socket or IP member of the System.Net.Sockets.SocketOptionLevel enumeration. Parameter optionName: Either the Linger, AddMembership, or DropMembership member of the System.Net.Sockets.SocketOptionName enumeration. Parameter optionValue: An instance of the System.Net.Sockets.LingerOption or System.Net.Sockets.MulticastOption class. Throws: : optionLevel, optionName, or optionValue specified an invalid value. Throws: : optionValue is null. Throws: : An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : A caller in the call stack does not have the required permissions. Throws: : The current instance has been disposed. Socket options determine the behavior of the current instance. Multiple options can be set on the current instance by calling this method multiple times. The following table summarizes the valid combinations of input parameters. When setting the System.Net.Sockets.SocketOptionName.Linger option, a System.ArgumentException exception is thrown if the System.Net.Sockets.LingerOption.LingerTime property of the System.Net.Sockets.LingerOption instance is less than zero or greater than System.UInt16.MaxValue . For more information on the System.Net.Sockets.SocketOptionName.Linger option, see the System.Net.Sockets.LingerOption class and the System.Net.Sockets.Socket.Shutdown(System.Net.Sockets.SocketShutdown) method. For more information on the System.Net.Sockets.SocketOptionName.AddMembership and System.Net.Sockets.SocketOptionName.DropMembership options, see the System.Net.Sockets.MulticastOption class. For socket options with values of type System.Int32 or System.Boolean, see the System.Net.Sockets.Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,System.Int32)(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, System.Int32) version of this method. |
public System.Void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, System.Byte[] optionValue) Sets socket options with values of type Byte[]. Parameter optionLevel: One of the values defined in the System.Net.Sockets.SocketOptionLevel enumeration. Parameter optionName: One of the values defined in the System.Net.Sockets.SocketOptionName enumeration. Parameter optionValue: A System.Byte array containing the value of the option. Throws: : An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : A caller in the call stack does not have the required permissions. Throws: : The current instance has been disposed. Socket options determine the behavior of the current instance. Multiple options can be set on the current instance by calling this method multiple times. For socket options with values of type System.Int32 or System.Boolean, see the System.Net.Sockets.Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,System.Int32)(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName , System.Int32) version of this method. For the System.Net.Sockets.SocketOptionName.AddMembership, System.Net.Sockets.SocketOptionName.DropMembership, or System.Net.Sockets.SocketOptionName.Linger socket options, see the System.Net.Sockets.Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,System.Int32)(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, System.Object) version of this method. |
public System.Void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, System.Int32 optionValue) Sets socket options with values of type System.Int32 and System.Boolean. Parameter optionLevel: One of the values defined in the System.Net.Sockets.SocketOptionLevel enumeration. Parameter optionName: One of the values defined in the System.Net.Sockets.SocketOptionName enumeration. Parameter optionValue: A System.Int32 containing the value of the option. Throws: : An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : A caller in the call stack does not have the required permissions. Throws: : The current instance has been disposed. Socket options determine the behavior of the current instance. Multiple options can be set on the current instance by calling this method multiple times. For a socket option with a System.Boolean data type, specify a non-zero optionValue to enable the option, and an optionValue equal to zero to disable the option. Socket options are grouped by level of protocol support. The following tables list the members of the System.Net.Sockets.SocketOptionName enumeration supported by each member of the System.Net.Sockets.SocketOptionLevel enumeration. Only members that have associated values of the System.Int32 and System.Boolean data types are listed. The following table lists the members of the System.Net.Sockets.SocketOptionName enumeration supported by the Socket member of the System.Net.Sockets.SocketOptionLevel enumeration. Options that do not require permission to access unmanaged code are noted. The following table lists the members of the System.Net.Sockets.SocketOptionName enumeration supported by the IP member of the System.Net.Sockets.SocketOptionLevel enumeration. These options require permission to access unmanaged code. The following table lists the members of the System.Net.Sockets.SocketOptionName enumeration supported by the Tcp member of the System.Net.Sockets.SocketOptionLevel enumeration. These options do not require permission to access unmanaged code. The following table lists the members of the System.Net.Sockets.SocketOptionName enumeration supported by the Udp member of the System.Net.Sockets.SocketOptionLevel enumeration. These options do not require permission to access unmanaged code. For the AddMembership, DropMembership, and Linger members of the System.Net.Sockets.SocketOptionName enumeration, see the System.Net.Sockets.Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,System.Int32)(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, System.Object) version of this method. |
public System.Void Shutdown(System.Net.Sockets.SocketShutdown how) Terminates the ability to send or receive data on a connected socket. Parameter how: One of the values defined in the System.Net.Sockets.SocketShutdown enumeration. Throws: : An error occurred while accessing the socket. For additional information on causes of the SocketException, see the System.Net.Sockets.SocketException class. Throws: : The current instance has been disposed. When how is set to System.Net.Sockets.SocketShutdown.Send , the socket on the other end of the connection is notified that the current instance will not send any more data. If the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method is subsequently called, a System.Net.Sockets.SocketException exception is thrown. When how is set to System.Net.Sockets.SocketShutdown.Receive, the socket on the other end of the connection is notified that the current instance will not receive any more data. After all the data currently queued on the current instance is received, any subsequent calls to the System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method cause a System.Net.Sockets.SocketException exception to be thrown. Setting how to System.Net.Sockets.SocketShutdown.Both terminates both sends and receives as described above. Once this occurs, the socket cannot be used. To free resources allocated by the current instance, call the System.Net.Sockets.Socket.Close method. Expected common usage is for the System.Net.Sockets.Socket.Shutdown(System.Net.Sockets.SocketShutdown) method to be called before the System.Net.Sockets.Socket.Close method to ensure that all pending data is sent or received. |
public System.Void System.IDisposable.Dispose() Implemented to support the System.IDisposable interface. [Note: For more information, see System.IDisposable.Dispose.] |
| Functions inherited from System.Object: |
|---|
public virtual System.Boolean Equals(System.Object obj) Determines whether the specified System.Object is equal to the current instance. Parameter obj: The System.Object to compare with the current instance. Returns: true if obj is equal to the current instance; otherwise, false. The statements listed below are required to be true for all implementations of the System.Object.Equals(System.Object) method. In the list, x, y, and z represent non-null object references. See System.Object.GetHashCode for additional required behaviors pertaining to the System.Object.Equals(System.Object) method. Implementations of System.Object.Equals(System.Object) should not throw exceptions. The System.Object.Equals(System.Object) method tests for referential equality , which means that System.Object.Equals(System.Object) returns true if the specified instance of Object and the current instance are the same instance; otherwise, it returns false . An implementation of the System.Object.Equals(System.Object) method is shown in the following C# code: public virtual bool Equals(Object obj) { return this == obj; } For some kinds of objects, it is desirable to have System.Object.Equals(System.Object) test for value equality instead of referential equality. Such implementations of Equals return true if the two objects have the same "value", even if they are not the same instance. The definition of what constitutes an object's "value" is up to the implementer of the type, but it is typically some or all of the data stored in the instance variables of the object. For example, the value of a System.String is based on the characters of the string; the Equals method of the System.String class returns true for any two string instances that contain exactly the same characters in the same order. When the Equals method of a base class provides value equality, an override of Equals in a class derived from that base class should invoke the inherited implementation of Equals . It is recommended (but not required) that types overriding System.Object.Equals(System.Object) also override System.Object.GetHashCode. Hashtables cannot be relied on to work correctly if this recommendation is not followed. If your programming language supports operator overloading, and if you choose to overload the equality operator for a given type, that type should override the Equals method. Such implementations of the Equals method should return the same results as the equality operator. Following this guideline will help ensure that class library code using Equals (such as System.Collections.ArrayList and System.Collections.Hashtable ) behaves in a manner that is consistent with the way the equality operator is used by application code. If you are implementing a value type, you should follow these guidelines: For reference types, the guidelines are as follows: If you implement System.IComparable on a given type, you should override Equals on that type. The System.Object.Equals(System.Object) method is called by methods in collections classes that perform search operations, including the System.Array.IndexOf(System.Array,System.Object) method and the System.Collections.ArrayList.Contains(System.Object) method. Example: Example 1: The following example contains two calls to the default implementation of System.Object.Equals(System.Object) . using System;
class MyClass {
static void Main() {
Object obj1 = new Object();
Object obj2 = new Object();
Console.WriteLine(obj1.Equals(obj2));
obj1 = obj2;
Console.WriteLine(obj1.Equals(obj2));
}
}
The output is False True Example 2: The following example shows a Point class that overrides the System.Object.Equals(System.Object) method to provide value equality and a class Point3D, which is derived from Point . Because Point's override of System.Object.Equals(System.Object) is the first in the inheritance chain to introduce value equality, the Equals method of the base class (which is inherited from System.Object and checks for referential equality) is not invoked. However, Point3D.Equals invokes Point.Equals because Point implements Equals in a manner that provides value equality. using System;
public class Point: object {
int x, y;
public override bool Equals(Object obj) {
//Check for null and compare run-time types.
if (obj == null || GetType() != obj.GetType()) return false;
Point p = (Point)obj;
return (x == p.x) && (y == p.y);
}
public override int GetHashCode() {
return x ^ y;
}
}
class Point3D: Point {
int z;
public override bool Equals(Object obj) {
return base.Equals(obj) && z == ((Point3D)obj).z;
}
public override int GetHashCode() {
return base.GetHashCode() ^ z;
}
}
The Point.Equals method checks that the obj
argument is non-null and that it references an instance of the same type as this
object. If either of those checks fail, the method returns false. The
System.Object.Equals(System.Object) method uses
System.Object.GetType to determine whether
the run-time types of the two objects are identical. (Note that
typeof is not used here because it returns the static type.) If
instead the method had used a check of the form
In Point3D.Equals , the inherited Equals method is invoked before anything else is done; the inherited Equals method checks to see that obj is non-null, that obj is an instance of the same class as this object, and that the inherited instance variables match. Only when the inherited Equals returns true does the method compare the instance variables introduced in the subclass. Specifically, the cast to Point3D is not executed unless obj has been determined to be of type Point3D or a subclass of Point3D . Example 3: In the previous example, operator == (the equality operator) is used to compare the individual instance variables. In some cases, it is appropriate to use the System.Object.Equals(System.Object) method to compare instance variables in an Equals implementation, as shown in the following example: using System;
class Rectangle {
Point a, b;
public override bool Equals(Object obj) {
if (obj == null || GetType() != obj.GetType()) return false;
Rectangle r = (Rectangle)obj;
//Use Equals to compare instance variables
return a.Equals(r.a) && b.Equals(r.b);
}
public override int GetHashCode() {
return a.GetHashCode() ^ b.GetHashCode();
}
}
Example 4: In some languages, such as C#, operator overloading is supported. When a type overloads operator ==, it should also override the System.Object.Equals(System.Object) method to provide the same functionality. This is typically accomplished by writing the Equals method in terms of the overloaded operator ==. For example: using System;
public struct Complex {
double re, im;
public override bool Equals(Object obj) {
return obj is Complex && this == (Complex)obj;
}
public override int GetHashCode() {
return re.GetHashCode() ^ im.GetHashCode();
}
public static bool operator ==(Complex x, Complex y) {
return x.re == y.re && x.im == y.im;
}
public static bool operator !=(Complex x, Complex y) {
return !(x == y);
}
}
Because Complex is a C# struct (a value type), it is known that there will be no subclasses of Complex . Therefore, the System.Object.Equals(System.Object) method need not compare the GetType() results for each object, but can instead use the is operator to check the type of the obj parameter. |
public static System.Boolean Equals(System.Object objA, System.Object objB) Determines whether two object references are equal. Parameter objA: First object to compare. Parameter objB: Second object to compare. Returns: true if one or more of the following statements is true: otherwise returns false. This static method checks for null references before it calls objA.Equals(objB ) and returns false if either objA or objB is null. If the Equals(object obj) implementation throws an exception, this method throws an exception. Example: The following example demonstrates the System.Object.Equals(System.Object) method. using System;
public class MyClass {
public static void Main() {
string s1 = "Tom";
string s2 = "Carol";
Console.WriteLine("Object.Equals(\"{0}\", \"{1}\") => {2}",
s1, s2, Object.Equals(s1, s2));
s1 = "Tom";
s2 = "Tom";
Console.WriteLine("Object.Equals(\"{0}\", \"{1}\") => {2}",
s1, s2, Object.Equals(s1, s2));
s1 = null;
s2 = "Tom";
Console.WriteLine("Object.Equals(null, \"{1}\") => {2}",
s1, s2, Object.Equals(s1, s2));
s1 = "Carol";
s2 = null;
Console.WriteLine("Object.Equals(\"{0}\", null) => {2}",
s1, s2, Object.Equals(s1, s2));
s1 = null;
s2 = null;
Console.WriteLine("Object.Equals(null, null) => {2}",
s1, s2, Object.Equals(s1, s2));
}
}
The output is Object.Equals("Tom", "Carol") => False Object.Equals("Tom", "Tom") => True Object.Equals(null, "Tom") => False Object.Equals("Carol", null) => False Object.Equals(null, null) => True |
public System.Void Finalize() Allows a System.Object to perform cleanup operations before the memory allocated for the System.Object is automatically reclaimed. During execution, System.Object.Finalize is automatically called after an object becomes inaccessible, unless the object has been exempted from finalization by a call to System.GC.SuppressFinalize(System.Object). During shutdown of an application domain, System.Object.Finalize is automatically called on objects that are not exempt from finalization, even those that are still accessible. System.Object.Finalize is automatically called only once on a given instance, unless the object is re-registered using a mechanism such as System.GC.ReRegisterForFinalize(System.Object) and System.GC.SuppressFinalize(System.Object) has not been subsequently called. Conforming implementations of the CLI are required to make every effort to ensure that for every object that has not been exempted from finalization, the System.Object.Finalize method is called after the object becomes inaccessible. However, there may be some circumstances under which Finalize is not called. Conforming CLI implementations are required to explicitly specify the conditions under which Finalize is not guaranteed to be called. For example, Finalize might not be guaranteed to be called in the event of equipment failure, power failure, or other catastrophic system failures. In addition to System.GC.ReRegisterForFinalize(System.Object) and System.GC.SuppressFinalize(System.Object), conforming implementations of the CLI are allowed to provide other mechanisms that affect the behavior of System.Object.Finalize . Any mechanisms provided are required to be specified by the CLI implementation. The order in which the Finalize methods of two objects are run is unspecified, even if one object refers to the other. The thread on which Finalize is run is unspecified. Every implementation of System.Object.Finalize in a derived type is required to call its base type's implementation of Finalize . This is the only case in which application code calls System.Object.Finalize . The System.Object.Finalize implementation does nothing. A type should implement Finalize when it uses unmanaged resources such as file handles or database connections that must be released when the managed object that uses them is reclaimed. Because Finalize methods may be invoked in any order (including from multiple threads), synchronization may be necessary if the Finalize method may interact with other objects, whether accessible or not. Furthermore, since the order in which Finalize is called is unspecified, implementers of Finalize (or of destructors implemented through overriding Finalize) must take care to correctly handle references to other objects, as their Finalize method may already have been invoked. In general, referenced objects should not be considered valid during finalization. See the System.IDisposable interface for an alternate means of disposing of resources. For C# developers: Destructors are the C# mechanism for performing cleanup operations. Destructors provide appropriate safeguards, such as automatically calling the base type's destructor. In C# code, System.Object.Finalize cannot be called or overridden. |
public virtual System.Int32 GetHashCode() Generates a hash code for the current instance. Returns: A System.Int32 containing the hash code for the current instance. System.Object.GetHashCode serves as a hash function for a specific type. A hash function is used to quickly generate a number (a hash code) corresponding to the value of an object. Hash functions are used with hashtables. A good hash function algorithm rarely generates hash codes that collide. For more information about hash functions, see The Art of Computer Programming , Vol. 3, by Donald E. Knuth. All implementations of System.Object.GetHashCode are required to ensure that for any two object references x and y, if x.Equals(y) == true, then x.GetHashCode() == y.GetHashCode(). Hash codes generated by System.Object.GetHashCode need not be unique. Implementations of System.Object.GetHashCode are not permitted to throw exceptions. The System.Object.GetHashCode implementation attempts to produce a unique hash code for every object, but the hash codes generated by this method are not guaranteed to be unique. Therefore, System.Object.GetHashCode may generate the same hash code for two different instances. It is recommended (but not required) that types overriding System.Object.GetHashCode also override System.Object.Equals(System.Object) . Hashtables cannot be relied on to work correctly if this recommendation is not followed. Use this method to obtain the hash code of an object. Hash codes should not be persisted (i.e. in a database or file) as they are allowed to change from run to run. Example: Example 1 In some cases, System.Object.GetHashCode is implemented to simply return an integer value. The following example illustrates an implementation of System.Int32.GetHashCode , which returns an integer value: using System;
public struct Int32 {
int value;
//other methods...
public override int GetHashCode() {
return value;
}
}
Example 2 Frequently, a type has multiple data members that can participate in generating the hash code. One way to generate a hash code is to combine these fields using an xor (exclusive or) operation, as shown in the following example: using System;
public struct Point {
int x;
int y;
//other methods
public override int GetHashCode() {
return x ^ y;
}
}
Example 3 The following example illustrates another case where the type's fields are combined using xor (exclusive or) to generate the hash code. Notice that in this example, the fields represent user-defined types, each of which implements System.Object.GetHashCode (and should implement System.Object.Equals(System.Object) as well): using System;
public class SomeType {
public override int GetHashCode() {
return 0;
}
}
public class AnotherType {
public override int GetHashCode() {
return 1;
}
}
public class LastType {
public override int GetHashCode() {
return 2;
}
}
public class MyClass {
SomeType a = new SomeType();
AnotherType b = new AnotherType();
LastType c = new LastType();
public override int GetHashCode () {
return a.GetHashCode() ^ b.GetHashCode() ^ c.GetHashCode();
}
}
Avoid implementing System.Object.GetHashCode in a manner that results in circular references. In other words, if AClass.GetHashCode calls BClass.GetHashCode, it should not be the case that BClass.GetHashCode calls AClass.GetHashCode. Example 4 In some cases, the data member of the class in which you are implementing System.Object.GetHashCode is bigger than a System.Int32. In such cases, you could combine the high order bits of the value with the low order bits using an XOR operation, as shown in the following example: using System;
public struct Int64 {
long value;
//other methods...
public override int GetHashCode() {
return ((int)value ^ (int)(value >> 32));
}
}
|
public System.Type GetType() Gets the type of the current instance. Returns: The instance of System.Type that represents the run-time type (the exact type) of the current instance. For two objects x and y that have identical run-time types, System.Object.ReferenceEquals(System.Object,System.Object)(x.GetType(),y.GetType()) returns true . Example: The following example demonstrates the fact that System.Object.GetType returns the run-time type of the current instance: using System;
public class MyBaseClass: Object {
}
public class MyDerivedClass: MyBaseClass {
}
public class Test {
public static void Main() {
MyBaseClass myBase = new MyBaseClass();
MyDerivedClass myDerived = new MyDerivedClass();
object o = myDerived;
MyBaseClass b = myDerived;
Console.WriteLine("mybase: Type is {0}", myBase.GetType());
Console.WriteLine("myDerived: Type is {0}", myDerived.GetType());
Console.WriteLine("object o = myDerived: Type is {0}", o.GetType());
Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType());
}
}
The output is mybase: Type is MyBaseClass myDerived: Type is MyDerivedClass object o = myDerived: Type is MyDerivedClass MyBaseClass b = myDerived: Type is MyDerivedClass |
protected System.Object MemberwiseClone() Creates a shallow copy of the current instance. Returns: A shallow copy of the current instance. The run-time type (the exact type) of the returned object is the same as the run-time type of the object that was copied. System.Object.MemberwiseClone creates a new instance of the same type as the current instance and then copies each of the object's non-static fields in a manner that depends on whether the field is a value type or a reference type. If the field is a value type, a bit-by-bit copy of all the field's bits is performed. If the field is a reference type, only the reference is copied. The algorithm for performing a shallow copy is as follows (in pseudo-code): for each instance field f in this instance if (f is a value type) bitwise copy the field if (f is a reference type) copy the reference end for loop This mechanism is referred to as a shallow copy because it copies rather than clones the non-static fields. Because System.Object.MemberwiseClone implements the above algorithm, for any object, a, the following statements are required to be true: System.Object.MemberwiseClone does not call any of the type's constructors. If System.Object.Equals(System.Object) has been overridden, a.MemberwiseClone().Equals(a) might return false . For an alternate copying mechanism, see System.ICloneable . System.Object.MemberwiseClone is protected (rather than public) to ensure that from verifiable code it is only possible to clone objects of the same class as the one performing the operation (or one of its subclasses). Although cloning an object does not directly open security holes, it does allow an object to be created without running any of its constructors. Since these constructors may establish important invariants, objects created by cloning may not have these invariants established, and this may lead to incorrect program behavior. For example, a constructor might add the new object to a linked list of all objects of this class, and cloning the object would not add the new object to that list -- thus operations that relied on the list to locate all instances would fail to notice the cloned object. By making the method protected, only objects of the same class (or a subclass) can produce a clone and implementers of those classes are (presumably) aware of the appropriate invariants and can arrange for them to be true without necessarily calling a constructor. Example: The following example shows a class called MyClass as well as a representation of the instance of MyClass returned by System.Object.MemberwiseClone . using System;
class MyBaseClass {
public static string CompanyName = "My Company";
public int age;
public string name;
}
class MyDerivedClass: MyBaseClass {
static void Main() {
//Create an instance of MyDerivedClass
//and assign values to its fields.
MyDerivedClass m1 = new MyDerivedClass();
m1.age = 42;
m1.name = "Sam";
//Do a shallow copy of m1
//and assign it to m2.
MyDerivedClass m2 = (MyDerivedClass) m1.MemberwiseClone();
}
}
A graphical representation of m1 and m2 might look like this
+---------------+
| 42 | m1
+---------------+
| +---------|-----------------> "Sam"
+---------------+ /|\
|
+---------------+ |
| 42 | | m2
+---------------+ |
| +--------|---------------------|
+---------------+
|
public static System.Boolean ReferenceEquals(System.Object objA, System.Object objB) Determines whether two object references are identical. Parameter objA: First object to compare. Parameter objB: Second object to compare. Returns: True if a and b refer to the same object or are both null references; otherwise, false. This static method provides a way to compare two objects for reference equality. It does not call any user-defined code, including overrides of System.Object.Equals(System.Object) . Example: using System;
class MyClass {
static void Main() {
object o = null;
object p = null;
object q = new Object();
Console.WriteLine(Object.ReferenceEquals(o, p));
p = q;
Console.WriteLine(Object.ReferenceEquals(p, q));
Console.WriteLine(Object.ReferenceEquals(o, p));
}
}
The output is True True False |
public virtual System.String ToString() Creates and returns a System.String representation of the current instance. Returns: A System.String representation of the current instance. System.Object.ToString returns a string whose content is intended to be understood by humans. Where the object contains culture-sensitive data, the string representation returned by System.Object.ToString takes into account the current system culture. For example, for an instance of the System.Double class whose value is zero, the implementation of System.Double.ToString might return "0.00" or "0,00" depending on the current UI culture. Although there are no exact requirements for the format of the returned string, it should as much as possible reflect the value of the object as perceived by the user. System.Object.ToString is equivalent to calling System.Object.GetType to obtain the System.Type object for the current instance and then returning the result of calling the System.Object.ToString implementation for that type. The value returned includes the full name of the type. It is recommended, but not required, that System.Object.ToString be overridden in a derived class to return values that are meaningful for that type. For example, the base data types, such as System.Int32, implement System.Object.ToString so that it returns the string form of the value the object represents. Subclasses that require more control over the formatting of strings than System.Object.ToString provides should implement System.IFormattable, whose System.Object.ToString method uses the culture of the current thread. Example: The following example outputs the textual description of the value of an object of type System.Object to the console. using System;
class MyClass {
static void Main() {
object o = new object();
Console.WriteLine (o.ToString());
}
}
The output is System.Object |
| Functions inherited from System.IDisposable: |
|---|
public System.Void Dispose() Performs application-defined tasks associated with freeing or resetting resources. This method is, by convention, used for all tasks associated with freeing resources held by an object, or preparing an object for reuse. When implementing the System.IDisposable.Dispose method, objects should seek to ensure that all held resources are freed by propagating the call through the containment hierarchy. For example, if an object A allocates an object B, and B allocates an object C, then A's System.IDisposable.Dispose implementation should call System.IDisposable.Dispose on B, which should in turn call System.IDisposable.Dispose on C. Objects should also call the System.IDisposable.Dispose method of their base class if the base class implements System.IDisposable. If an object's System.IDisposable.Dispose method is called more than once, the object should ignore all calls after the first one. The object should not throw an exception if its System.IDisposable.Dispose method is called multiple times. System.IDisposable.Dispose may throw an exception if an error occurs because a resource has already been freed and System.IDisposable.Dispose had not been called previously. A resource type may use a particular convention to denote an allocated state versus a freed state. An example of this is stream classes, which are traditionally thought of as open or closed. Classes that have such conventions may choose to implement a public method with a customized name, which calls the System.IDisposable.Dispose method. Because the System.IDisposable.Dispose method must be called explicitly, objects that implement System.IDisposable should also implement a finalizer to handle freeing resources when System.IDisposable.Dispose is not called. By default, the garbage collector will automatically call an object's finalizer prior to reclaiming its memory. However, once the System.IDisposable.Dispose method has been called, it is typically unnecessary and/or undesirable for the garbage collector to call the disposed object's finalizer. To prevent automatic finalization, System.IDisposable.Dispose implementations can call System.GC.SuppressFinalize(System.Object). For additional information on implementing finalizers, see System.GC and System.Object.Finalize. Example: Resource classes should follow the pattern illustrated by this example: class ResourceWrapper : BaseType, IDisposable {
// Pointer to a external resource.
private int handle;
private OtherResource otherRes; //Other resource you use.
private bool disposed = false;
public ResourceWrapper () {
handle = //Allocate on the unmanaged side.
otherRes = new OtherResource (...);
}
// Free your own state.
private void freeState () {
if (!disposed) {
CloseHandle (handle);
dispose = true;
}
}
// Free your own state, call dispose on all state you hold,
// and take yourself off the Finalization queue.
public void Dispose () {
freeState ();
OtherRes.Dispose();
// If base type implements dispose, call it.
base.Dispose();
GC.SuppressFinalize(this);
}
// Free your own state (not other state you hold)
// and give your base class a chance to finalize.
~ResourceWrapper (){
freeState();
}
}
|