Roadmap › ADO.NET — Connected & Disconnected Data Access › Module: Transactions, Pooling and Performance
Lessons in this course (9)
8. Bulk operations and async
IntermediateMediumLesson 8 of 9
csharp
using var bulk = new SqlBulkCopy(conn, SqlBulkCopyOptions.TableLock, tx)
{
DestinationTableName = "dbo.StagingSales",
BatchSize = 10_000,
BulkCopyTimeout = 600
};
bulk.ColumnMappings.Add("Date", "SaleDate");
bulk.ColumnMappings.Add("Amount", "Amount");
await bulk.WriteToServerAsync(dataTableOrDataReader); // streams rows using the bulk insert protocolSqlBulkCopyloads millions of rows in seconds vs minutes with row-by-row INSERTs.- Use async APIs (
OpenAsync,ExecuteReaderAsync,ReadAsync) in web apps to free threads during I/O. CommandTimeoutdefault is 30 seconds; set it per command for long reports.- Batch many statements with
SqlBatch/DbBatch(.NET 6+) or TVPs instead of N round trips.