SendAsync is the asynchronous socket operation for handing data to the local network stack. It returns immediately with a Task<int>; the task completes when synchronous Send would return, and its result is the number of bytes accepted—not confirmation that the data reached the peer. section 6.1
In an asynchronous server, SendAsync helps avoid blocking a request-handling thread while data is being transferred.
- Pass the data buffer and SocketFlags.None. section 6.1
- Await the returned Task<int> to obtain the accepted byte count. section 6.1
- Use ReceiveAsync for the corresponding asynchronous read and Shutdown for graceful closure. section 6.1
Asynchronous file server
A server reads file chunks with ReadAsync and awaits connection.SendAsync for each chunk, allowing asynchronous connection handling instead of one dedicated thread per request. section 6.1
Listing 6.3 Asynchronous server
using System.Net;
using System.Net.Sockets;
var listenSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
listenSocket.Bind(new IPEndPoint(IPAddress.Any, 7777));
listenSocket.Listen(100);
while(true)
{
var connection = await listenSocket.AcceptAsync(); #1
Task.Run(async () => #2
{
using var file = new FileStream("somefile.bin",
FileMode.Open, FileAccess.Read);
var buffer = new byte[1024*1024];
while (true)
{
int read = await file.ReadAsync(buffer,
0, buffer.Length)); #3
if (read != 0)
{
await connection.SendAsync(
new ArraySegment<byte>(buffer, 0, read),
SocketFlags.None); #4
}
else
{
connection.Shutdown(SocketShutdown.Both);
connection.Dispose();
return;
}
}
});
}
View the complete asynchronous server listing, including AcceptAsync, ReadAsync, and SendAsync in one runnable flow. section 6.1

