liveBook · Manning

SendAsync

As explained in C# Concurrency: Asynchronous and multithreaded programming

SendAsync is an asynchronous socket operation that transfers data and represents completion with a task containing the accepted byte count.

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

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Defines task completion and accepted-byte semantics, then demonstrates SendAsync inside an asynchronous file-serving loop.
Examples
Uses an asynchronous TCP file server that sends one-megabyte buffer segments after reading them asynchronously.
What you can do after
Apply it via C# Socket APIs to asynchronously send buffer segments and inspect the accepted byte count.
How it connects
Links SendAsync with Socket, AcceptAsync, ReadAsync, ReceiveAsync, ConnectAsync, Shutdown, and Task.

Also explained in

Compare how 2 books explain SendAsync →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C# Concurrency: Asynchronous and multithreaded programming. The section links point to the parts of the book it draws on.