TcpClientAsyncResult Class
Namespace: System.Net.Sockets
Assembly: System.Net.Sockets.dll
Represents the result of an asynchronous socket operation initiated by a TcpClient
class.
Remarks
The TcpClientAsyncResult
class is an internal class used by the TcpClient
class to manage the state and results of asynchronous operations like connecting, sending, and receiving data. You typically do not interact with this class directly. Instead, you use the asynchronous methods provided by TcpClient
, such as ConnectAsync
, SendAsync
, and ReceiveAsync
, which return Task
or Task<TResult>
objects that abstract away the underlying asynchronous result management.
Methods
This class does not expose any public methods directly that you would typically call. Its methods are part of the internal implementation of asynchronous operations.
Properties
The following properties are part of the internal implementation:
Name | Type | Description |
---|---|---|
AsyncState | object |
Gets the state object provided to the asynchronous operation. |
CompletedSynchronously | bool |
Gets a value indicating whether the asynchronous operation completed synchronously. |
IsCompleted | bool |
Gets a value indicating whether the asynchronous operation has completed. |
AsyncWaitHandle | System.Threading.WaitHandle |
Gets a handle used to wait for the completion of an asynchronous operation. |
Example
While you don't directly use TcpClientAsyncResult
, here's an example of how to use asynchronous methods of TcpClient
:
// This is a conceptual example demonstrating the usage of async methods.
// TcpClientAsyncResult is an internal class not directly instantiated by the user.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class AsyncTcpClientExample
{
public static async Task RunAsync()
{
using (var client = new TcpClient())
{
try
{
// Asynchronously connect to a server
await client.ConnectAsync("example.com", 80);
Console.WriteLine("Connected!");
// Get the network stream for sending/receiving data
using (var stream = client.GetStream())
{
// Asynchronously send data
byte[] message = Encoding.ASCII.GetBytes("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
await stream.WriteAsync(message, 0, message.Length);
Console.WriteLine("Sent: GET / HTTP/1.1");
// Asynchronously receive data
byte[] buffer = new byte[1024];
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
string responseData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received: " + responseData.Substring(0, Math.Min(bytesRead, 200)) + "...");
}
}
catch (SocketException ex)
{
Console.WriteLine($"SocketException: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General Exception: {ex.Message}");
}
}
}
public static void Main(string[] args)
{
RunAsync().GetAwaiter().GetResult();
}
}