Språk

Genomgång: Använda BatchBlock och BatchedJoinBlock för att förbättra effektiviteten

TPL-dataflödesbiblioteket innehåller klasserna System.Threading.Tasks.Dataflow.BatchBlock<T> och System.Threading.Tasks.Dataflow.BatchedJoinBlock<T1,T2> så att du kan ta emot och buffra data från en eller flera källor och sedan sprida dessa buffrade data som en samling. Den här batchbearbetningsmekanismen är användbar när du samlar in data från en eller flera källor och sedan bearbetar flera dataelement som en batch. Tänk dig till exempel ett program som använder dataflöde för att infoga poster i en databas. Den här åtgärden kan vara effektivare om flera objekt infogas samtidigt i stället för en i taget sekventiellt. Det här dokumentet beskriver hur du använder klassen BatchBlock<T> för att förbättra effektiviteten för sådana databasinfogningsåtgärder. Den beskriver också hur du använder klassen BatchedJoinBlock<T1,T2> för att samla in både resultaten och eventuella undantag som inträffar när programmet läser från en databas.

Anmärkning

TPL-dataflödesbiblioteket ( System.Threading.Tasks.Dataflow namnområdet) ingår i .NET 6 och senare versioner. För .NET Framework- och .NET Standard-projekt måste du installera 📦 NuGet-paketet System.Threading.Tasks.Dataflow.

Förutsättningar

  1. Läs avsnittet Kopplingsblock i dokumentet Dataflöde innan du påbörjar den här genomgången.

  2. Installera .NET 10 SDK. Använd en utvecklingsdatabas, inte en produktionsdatabas.

Skapa en SQL-databas

Skapa eller koppla till en SQL-databas på en av följande plattformar:

Ange SQL_CONNECTION_STRING-miljövariabeln med en anslutningssträng för utvecklingsdatabasen. Använd till exempel Server=<server>,<port>;Database=<database>;User ID=<user_id>;Password=<password>;Encrypt=true;TrustServerCertificate=false. Ange den faktiska hemligheten i din lokala miljö, inte i källkoden.

För en container för lokal utveckling med ett självsignerat certifikat, använd TrustServerCertificate=true endast för den utvecklingsanslutningen. För produktionsanslutningar använder du ett betrott servercertifikat och håller certifikatverifiering aktiverat.

Exemplet skapar en unikt namngiven global tillfällig tabell i tempdb. En öppen anslutning håller tabellen tillgänglig för arbetaranslutningarna. Programmet återställer bara sin egen tabell mellan demonstrationer och tar bort den när demonstrationen slutar. Du behöver inte Northwind eller SQL Server Compact.

Skapa konsolprogrammet

  1. I Visual Studio skapar du ett Visual C#- eller Visual Basic-konsolprogram projekt. I det här dokumentet heter projektet DataflowBatchDatabase.

  2. Använd .NET 10 som målplattform och installera Microsoft.Data.SqlClient NuGet-paketet. För Microsoft Entra ID autentisering med Microsoft.Data.SqlClient 7 och senare versioner, installera även Microsoft.Data.SqlClient.Extensions.Azure. API:erna för dataflöde ingår i .NET 10.

  3. Ersätt den genererade koden i Program.cs (Program.vb för Visual Basic) med det fullständiga exemplet eller följ stegen i den här genomgången för att sammanställa det. Börja med dessa using (Importsi Visual Basic) instruktioner.

    using System;
    using System.Collections.Generic;
    using Microsoft.Data.SqlClient;
    using System.Diagnostics;
    using System.Threading.Tasks.Dataflow;
    
    Imports System.Data
    Imports Microsoft.Data.SqlClient
    Imports System.Collections.Generic
    Imports System.Threading.Tasks.Dataflow
    
    
  4. Lägg till följande datamedlemmar i klassen Program.

    // The number of employees to add to the database.
    // TODO: Change this value to experiment with different numbers of
    // employees to insert into the database.
    static readonly int s_insertCount = 256;
    
    // The size of a single batch of employees to add to the database.
    // TODO: Change this value to experiment with different batch sizes.
    static readonly int s_insertBatchSize = 96;
    
    static readonly string s_employeeTable =
       "##DataflowEmployees_" + Guid.NewGuid().ToString("N");
    
    ' The number of employees to add to the database.
    ' TODO: Change this value to experiment with different numbers of 
    ' employees to insert into the database.
    Private Shared ReadOnly s_insertCount As Integer = 256
    
    ' The size of a single batch of employees to add to the database.
    ' TODO: Change this value to experiment with different batch sizes.
    Private Shared ReadOnly s_insertBatchSize As Integer = 96
    
    Private Shared ReadOnly s_employeeTable As String =
        "##DataflowEmployees_" & Guid.NewGuid().ToString("N")
    

Definiera klassen Anställd

Lägg till klassen Program i klassen Employee.

// Describes an employee. Each property maps to a
// column in the sample employee table.
class Employee
{
   public int EmployeeID { get; set; }
   public string LastName { get; set; }
   public string FirstName { get; set; }

   // A random number generator that helps tp generate
   // Employee property values.
   static readonly Random s_rand = new Random(42);

   // Possible random first names.
   static readonly string[] s_firstNames =
          { "Tom", "Mike", "Ruth", "Bob", "John" };
   // Possible random last names.
   static readonly string[] s_lastNames =
          { "Jones", "Smith", "Johnson", "Walker" };

   // Creates an Employee object that contains random
   // property values.
   public static Employee Random()
   {
      return new Employee
      {
         EmployeeID = -1,
         LastName = s_lastNames[s_rand.Next() % s_lastNames.Length],
         FirstName = s_firstNames[s_rand.Next() % s_firstNames.Length]
      };
   }
}
' Describes an employee. Each property maps to a 
' column in the sample employee table.
Private Class Employee
    Public Property EmployeeID() As Integer
    Public Property LastName() As String
    Public Property FirstName() As String

    ' A random number generator that helps tp generate
    ' Employee property values.
    Private Shared ReadOnly s_rand As New Random(42)

    ' Possible random first names.
    Private Shared ReadOnly s_firstNames() As String =
        {"Tom", "Mike", "Ruth", "Bob", "John"}
    ' Possible random last names.
    Private Shared ReadOnly s_lastNames() As String =
        {"Jones", "Smith", "Johnson", "Walker"}

    ' Creates an Employee object that contains random 
    ' property values.
    Public Shared Function Random() As Employee
        Return New Employee With {
            .EmployeeID = -1,
            .LastName = s_lastNames(s_rand.Next() Mod s_lastNames.Length),
            .FirstName = s_firstNames(s_rand.Next() Mod s_firstNames.Length)
        }
    End Function
End Class

Klassen Employee innehåller tre egenskaper, EmployeeID, LastNameoch FirstName. Dessa egenskaper motsvarar kolumnerna Employee ID, Last Nameoch First Name i den temporära arbetstagartabellen. I den här demonstrationen definierar klassen Employee även metoden Random, som skapar ett Employee objekt som har slumpmässiga värden för sina egenskaper.

Definiera medarbetardatabasåtgärder

Lägg till metoderna Program, InsertEmployeesoch GetEmployeeCount i GetEmployeeID-klassen.

// Adds new employee records to the database.
static void InsertEmployees(Employee[] employees, string connectionString)
{
   using (SqlConnection connection =
      new SqlConnection(connectionString))
   {
      try
      {
         // Create the SQL command.
         SqlCommand command = new SqlCommand(
            $"INSERT INTO [{s_employeeTable}] ([Last Name], [First Name])" +
            "VALUES (@lastName, @firstName)",
            connection);

         connection.Open();
         for (int i = 0; i < employees.Length; i++)
         {
            // Set parameters.
            command.Parameters.Clear();
            command.Parameters.AddWithValue("@lastName", employees[i].LastName);
            command.Parameters.AddWithValue("@firstName", employees[i].FirstName);

            // Execute the command.
            command.ExecuteNonQuery();
         }
      }
      finally
      {
         connection.Close();
      }
   }
}

// Retrieves the number of entries in the sample employee table.
static int GetEmployeeCount(string connectionString)
{
   int result = 0;
   using (SqlConnection sqlConnection =
      new SqlConnection(connectionString))
   {
      SqlCommand sqlCommand = new SqlCommand(
         $"SELECT COUNT(*) FROM [{s_employeeTable}]", sqlConnection);

      sqlConnection.Open();
      try
      {
         result = (int)sqlCommand.ExecuteScalar();
      }
      finally
      {
         sqlConnection.Close();
      }
   }
   return result;
}

// Retrieves the ID of the first employee that has the provided name.
static int GetEmployeeID(string lastName, string firstName,
   string connectionString)
{
   using (SqlConnection connection =
      new SqlConnection(connectionString))
   {
      SqlCommand command = new SqlCommand(
         $"SELECT TOP (1) [Employee ID] FROM [{s_employeeTable}] " +
         "WHERE [Last Name] = @lastName AND [First Name] = @firstName ORDER BY [Employee ID]",
         connection);

      command.Parameters.Add("@lastName", System.Data.SqlDbType.NVarChar).Value = lastName;
      command.Parameters.Add("@firstName", System.Data.SqlDbType.NVarChar).Value = firstName;

      connection.Open();
      try
      {
         object result = command.ExecuteScalar();
         if (result == null)
            throw new KeyNotFoundException("No matching employee.");
         return (int)result;
      }
      finally
      {
         connection.Close();
      }
   }
}
' Adds new employee records to the database.
Private Shared Sub InsertEmployees(ByVal employees() As Employee, ByVal connectionString As String)
    Using connection As New SqlConnection(connectionString)
        Try
            ' Create the SQL command.
            Dim command As New SqlCommand($"INSERT INTO [{s_employeeTable}] ([Last Name], [First Name]) VALUES (@lastName, @firstName)", connection)

            connection.Open()
            For i As Integer = 0 To employees.Length - 1
                ' Set parameters.
                command.Parameters.Clear()
                command.Parameters.Add("@lastName", SqlDbType.NVarChar).Value = employees(i).LastName
                command.Parameters.Add("@firstName", SqlDbType.NVarChar).Value = employees(i).FirstName

                ' Execute the command.
                command.ExecuteNonQuery()
            Next i
        Finally
            connection.Close()
        End Try
    End Using
End Sub

' Retrieves the number of entries in the sample employee table.
Private Shared Function GetEmployeeCount(ByVal connectionString As String) As Integer
    Dim result As Integer = 0
    Using sqlConnection As New SqlConnection(connectionString)
        Dim sqlCommand As New SqlCommand($"SELECT COUNT(*) FROM [{s_employeeTable}]", sqlConnection)

        sqlConnection.Open()
        Try
            result = CInt(Fix(sqlCommand.ExecuteScalar()))
        Finally
            sqlConnection.Close()
        End Try
    End Using
    Return result
End Function

' Retrieves the ID of the first employee that has the provided name.
Private Shared Function GetEmployeeID(ByVal lastName As String, ByVal firstName As String, ByVal connectionString As String) As Integer
    Using connection As New SqlConnection(connectionString)
        Dim query As String = $"SELECT TOP (1) [Employee ID] FROM [{s_employeeTable}] WHERE [Last Name] = @lastName AND [First Name] = @firstName ORDER BY [Employee ID]"
        Dim command As New SqlCommand(query, connection)
        command.Parameters.Add("@lastName", SqlDbType.NVarChar, 50).Value = lastName
        command.Parameters.Add("@firstName", SqlDbType.NVarChar, 50).Value = firstName

        connection.Open()
        Try
            Dim result = command.ExecuteScalar()
            If result Is Nothing Then
                Throw New KeyNotFoundException("No matching employee.")
            End If
            Return CInt(result)
        Finally
            connection.Close()
        End Try
    End Using
End Function

InsertEmployees-metoden lägger till nya medarbetares poster i den tillfälliga tabellen. Metoden GetEmployeeCount hämtar antalet poster i den tabellen. Metoden GetEmployeeID hämtar identifieraren för den första medarbetaren som har det angivna namnet eller genererar KeyNotFoundException om ingen anställd matchar. Varje metod tar emot anslutningssträngen för din utvecklingsdatabas.

Lägga till medarbetardata i databasen utan att använda buffring

Lägg till metoderna Program och AddEmployees i klassen PostRandomEmployees.

// Posts random Employee data to the provided target block.
static void PostRandomEmployees(ITargetBlock<Employee> target, int count)
{
   Console.WriteLine($"Adding {count} entries to Employee table...");

   for (int i = 0; i < count; i++)
   {
      target.Post(Employee.Random());
   }
}

// Adds random employee data to the database by using dataflow.
static void AddEmployees(string connectionString, int count)
{
   // Create an ActionBlock<Employee> object that adds a single
   // employee entry to the database.
   var insertEmployee = new ActionBlock<Employee>(e =>
      InsertEmployees(new Employee[] { e }, connectionString));

   // Post several random Employee objects to the dataflow block.
   PostRandomEmployees(insertEmployee, count);

   // Set the dataflow block to the completed state and wait for
   // all insert operations to complete.
   insertEmployee.Complete();
   insertEmployee.Completion.Wait();
}
' Posts random Employee data to the provided target block.
Private Shared Sub PostRandomEmployees(ByVal target As ITargetBlock(Of Employee), ByVal count As Integer)
    Console.WriteLine("Adding {0} entries to Employee table...", count)

    For i As Integer = 0 To count - 1
        target.Post(Employee.Random())
    Next i
End Sub

' Adds random employee data to the database by using dataflow.
Private Shared Sub AddEmployees(ByVal connectionString As String, ByVal count As Integer)
    ' Create an ActionBlock<Employee> object that adds a single
    ' employee entry to the database.
    Dim insertEmployee = New ActionBlock(Of Employee)(Sub(e) InsertEmployees(New Employee() {e}, connectionString))

    ' Post several random Employee objects to the dataflow block.
    PostRandomEmployees(insertEmployee, count)

    ' Set the dataflow block to the completed state and wait for 
    ' all insert operations to complete.
    insertEmployee.Complete()
    insertEmployee.Completion.Wait()
End Sub

Metoden AddEmployees lägger till slumpmässiga medarbetardata i databasen med hjälp av dataflödet. Det skapar ett ActionBlock<TInput> objekt som anropar metoden InsertEmployees för att lägga till en anställds post i databasen. Metoden AddEmployees anropar sedan metoden PostRandomEmployees för att publicera flera Employee objekt till ActionBlock<TInput>-objektet. Metoden AddEmployees väntar sedan på att alla infogningsåtgärder ska slutföras.

Använda buffring för att lägga till personaldata i databasen

Lägg till metoden Program i klassen AddEmployeesBatched.

// Adds random employee data to the database by using dataflow.
// This method is similar to AddEmployees except that it uses batching
// to add multiple employees to the database at a time.
static void AddEmployeesBatched(string connectionString, int batchSize,
   int count)
{
   // Create a BatchBlock<Employee> that holds several Employee objects and
   // then propagates them out as an array.
   var batchEmployees = new BatchBlock<Employee>(batchSize);

   // Create an ActionBlock<Employee[]> object that adds multiple
   // employee entries to the database.
   var insertEmployees = new ActionBlock<Employee[]>(a =>
      InsertEmployees(a, connectionString));

   // Link the batch block to the action block.
   batchEmployees.LinkTo(insertEmployees);

   // When the batch block completes, set the action block also to complete.
   batchEmployees.Completion.ContinueWith(delegate { insertEmployees.Complete(); });

   // Post several random Employee objects to the batch block.
   PostRandomEmployees(batchEmployees, count);

   // Set the batch block to the completed state and wait for
   // all insert operations to complete.
   batchEmployees.Complete();
   insertEmployees.Completion.Wait();
}
' Adds random employee data to the database by using dataflow.
' This method is similar to AddEmployees except that it uses batching
' to add multiple employees to the database at a time.
Private Shared Sub AddEmployeesBatched(ByVal connectionString As String, ByVal batchSize As Integer, ByVal count As Integer)
    ' Create a BatchBlock<Employee> that holds several Employee objects and
    ' then propagates them out as an array.
    Dim batchEmployees = New BatchBlock(Of Employee)(batchSize)

    ' Create an ActionBlock<Employee[]> object that adds multiple
    ' employee entries to the database.
    Dim insertEmployees = New ActionBlock(Of Employee())(Sub(a) Program.InsertEmployees(a, connectionString))

    ' Link the batch block to the action block.
    batchEmployees.LinkTo(insertEmployees)

    ' When the batch block completes, set the action block also to complete.
    batchEmployees.Completion.ContinueWith(Sub() insertEmployees.Complete())

    ' Post several random Employee objects to the batch block.
    PostRandomEmployees(batchEmployees, count)

    ' Set the batch block to the completed state and wait for 
    ' all insert operations to complete.
    batchEmployees.Complete()
    insertEmployees.Completion.Wait()
End Sub

Den här metoden liknar AddEmployees, förutom att den också använder klassen BatchBlock<T> för att buffra flera Employee-objekt innan dessa skickas till ActionBlock<TInput>-objektet. Eftersom BatchBlock<T>-klassen sprider ut flera element som en samling ändras det ActionBlock<TInput> objektet så att det fungerar på en matris med Employee objekt. Precis som i metoden AddEmployees anropar AddEmployeesBatched metoden PostRandomEmployees för att publicera flera Employee objekt. men AddEmployeesBatched postar dessa objekt till det BatchBlock<T> objektet. Metoden AddEmployeesBatched väntar också på att alla infogningsåtgärder ska slutföras.

Använda buffrad koppling för att läsa medarbetardata från databasen

Lägg till metoden Program i klassen GetRandomEmployees.

// Displays information about several random employees to the console.
static void GetRandomEmployees(string connectionString, int batchSize,
   int count)
{
   // Create a BatchedJoinBlock<Employee, Exception> object that holds
   // both employee and exception data.
   var selectEmployees = new BatchedJoinBlock<Employee, Exception>(batchSize);

   // Holds the total number of exceptions that occurred.
   int totalErrors = 0;

   // Create an action block that prints employee and error information
   // to the console.
   var printEmployees =
      new ActionBlock<Tuple<IList<Employee>, IList<Exception>>>(data =>
      {
         // Print information about the employees in this batch.
         Console.WriteLine("Received a batch...");
         foreach (Employee e in data.Item1)
         {
            Console.WriteLine($"Last={e.LastName} First={e.FirstName} ID={e.EmployeeID}");
         }

         // Print the error count for this batch.
         Console.WriteLine($"There were {data.Item2.Count} errors in this batch...");

         // Update total error count.
         totalErrors += data.Item2.Count;
      });

   // Link the batched join block to the action block.
   selectEmployees.LinkTo(printEmployees);

   // When the batched join block completes, set the action block also to complete.
   selectEmployees.Completion.ContinueWith(delegate { printEmployees.Complete(); });

   // Try to retrieve the ID for several random employees.
   Console.WriteLine("Selecting random entries from Employees table...");
   for (int i = 0; i < count; i++)
   {
      try
      {
         // Create a random employee.
         Employee e = Employee.Random();

         // Try to retrieve the ID for the employee from the database.
         e.EmployeeID = GetEmployeeID(e.LastName, e.FirstName, connectionString);

         // Post the Employee object to the Employee target of
         // the batched join block.
         selectEmployees.Target1.Post(e);
      }
      catch (KeyNotFoundException e)
      {
         // GetEmployeeID throws KeyNotFoundException when there is
         // no such employee with the given name. When this happens,
         // post the Exception object to the Exception target of
         // the batched join block.
         selectEmployees.Target2.Post(e);
      }
   }

   // Set the batched join block to the completed state and wait for
   // all retrieval operations to complete.
   selectEmployees.Complete();
   printEmployees.Completion.Wait();

   // Print the total error count.
   Console.WriteLine($"Finished. There were {totalErrors} total errors.");
}
' Displays information about several random employees to the console.
Private Shared Sub GetRandomEmployees(ByVal connectionString As String, ByVal batchSize As Integer, ByVal count As Integer)
    ' Create a BatchedJoinBlock<Employee, Exception> object that holds
    ' both employee and exception data.
    Dim selectEmployees = New BatchedJoinBlock(Of Employee, Exception)(batchSize)

    ' Holds the total number of exceptions that occurred.
    Dim totalErrors As Integer = 0

    ' Create an action block that prints employee and error information
    ' to the console.
    Dim printEmployees = New ActionBlock(Of Tuple(Of IList(Of Employee), IList(Of Exception)))(
        Sub(data)
            ' Print information about the employees in this batch.
            ' Print the error count for this batch.
            ' Update total error count.
            Console.WriteLine("Received a batch...")
            For Each e As Employee In data.Item1
                Console.WriteLine("Last={0} First={1} ID={2}", e.LastName, e.FirstName, e.EmployeeID)
            Next e
            Console.WriteLine("There were {0} errors in this batch...", data.Item2.Count)
            totalErrors += data.Item2.Count
        End Sub)

    ' Link the batched join block to the action block.
    selectEmployees.LinkTo(printEmployees)

    ' When the batched join block completes, set the action block also to complete.
    selectEmployees.Completion.ContinueWith(Sub() printEmployees.Complete())

    ' Try to retrieve the ID for several random employees.
    Console.WriteLine("Selecting random entries from Employees table...")
    For i As Integer = 0 To count - 1
        Try
            ' Create a random employee.
            Dim e As Employee = Employee.Random()

            ' Try to retrieve the ID for the employee from the database.
            e.EmployeeID = GetEmployeeID(e.LastName, e.FirstName, connectionString)

            ' Post the Employee object to the Employee target of 
            ' the batched join block.
            selectEmployees.Target1.Post(e)
        Catch e As KeyNotFoundException
            ' GetEmployeeID throws KeyNotFoundException when there is
            ' no such employee with the given name. When this happens,
            ' post the Exception object to the Exception target of
            ' the batched join block.
            selectEmployees.Target2.Post(e)
        End Try
    Next i

    ' Set the batched join block to the completed state and wait for 
    ' all retrieval operations to complete.
    selectEmployees.Complete()
    printEmployees.Completion.Wait()

    ' Print the total error count.
    Console.WriteLine("Finished. There were {0} total errors.", totalErrors)
End Sub

Den här metoden skriver ut information om slumpmässiga anställda till konsolen. Den skapar flera slumpmässiga Employee objekt och anropar metoden GetEmployeeID för att hämta den unika identifieraren för varje objekt. Eftersom metoden GetEmployeeID genererar ett undantag om det inte finns någon matchande medarbetare med angivna för- och efternamn använder metoden GetRandomEmployees klassen BatchedJoinBlock<T1,T2> för att lagra Employee objekt för lyckade anrop till GetEmployeeID och System.Exception objekt för anrop som misslyckas. Det ActionBlock<TInput> objektet i det här exemplet fungerar på ett Tuple<T1,T2> objekt som innehåller en lista över Employee objekt och en lista över Exception objekt. Det BatchedJoinBlock<T1,T2> objektet sprider ut dessa data när summan av det mottagna Employee och Exception objektantalet är lika med batchstorleken.

Det fullständiga exemplet

I följande exempel visas den fullständiga koden. Metoden Main jämför den tid som krävs för att utföra batchbaserade databasinfogningar jämfört med tiden för att utföra icke-batchbaserade databasinfogningar. Det visar också användningen av buffrad koppling för att läsa medarbetardata från databasen och även rapportera fel.

Båda insättningsdemonstrationerna börjar med noll rader och slutar med 256 rader. Den sista demonstrationen infogar 16 rader och utför 10 sökningar. Varje batch återanvänder en anslutning för sina infogningar. det kör fortfarande ett kommando per anställd. Tidsåtgången beror på din server och ditt nätverk och är inte en allmän prestandagaranti.

using System;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using System.Diagnostics;
using System.Threading.Tasks.Dataflow;

// Demonstrates how to use batched dataflow blocks to improve
// the performance of database operations.
namespace DataflowBatchDatabase
{
   class Program
   {
      // The number of employees to add to the database.
      // TODO: Change this value to experiment with different numbers of
      // employees to insert into the database.
      static readonly int s_insertCount = 256;

      // The size of a single batch of employees to add to the database.
      // TODO: Change this value to experiment with different batch sizes.
      static readonly int s_insertBatchSize = 96;

      static readonly string s_employeeTable =
         "##DataflowEmployees_" + Guid.NewGuid().ToString("N");

      // Describes an employee. Each property maps to a
      // column in the sample employee table.
      class Employee
      {
         public int EmployeeID { get; set; }
         public string LastName { get; set; }
         public string FirstName { get; set; }

         // A random number generator that helps tp generate
         // Employee property values.
         static readonly Random s_rand = new Random(42);

         // Possible random first names.
         static readonly string[] s_firstNames =
                { "Tom", "Mike", "Ruth", "Bob", "John" };
         // Possible random last names.
         static readonly string[] s_lastNames =
                { "Jones", "Smith", "Johnson", "Walker" };

         // Creates an Employee object that contains random
         // property values.
         public static Employee Random()
         {
            return new Employee
            {
               EmployeeID = -1,
               LastName = s_lastNames[s_rand.Next() % s_lastNames.Length],
               FirstName = s_firstNames[s_rand.Next() % s_firstNames.Length]
            };
         }
      }

      // Adds new employee records to the database.
      static void InsertEmployees(Employee[] employees, string connectionString)
      {
         using (SqlConnection connection =
            new SqlConnection(connectionString))
         {
            try
            {
               // Create the SQL command.
               SqlCommand command = new SqlCommand(
                  $"INSERT INTO [{s_employeeTable}] ([Last Name], [First Name])" +
                  "VALUES (@lastName, @firstName)",
                  connection);

               connection.Open();
               for (int i = 0; i < employees.Length; i++)
               {
                  // Set parameters.
                  command.Parameters.Clear();
                  command.Parameters.AddWithValue("@lastName", employees[i].LastName);
                  command.Parameters.AddWithValue("@firstName", employees[i].FirstName);

                  // Execute the command.
                  command.ExecuteNonQuery();
               }
            }
            finally
            {
               connection.Close();
            }
         }
      }

      // Retrieves the number of entries in the sample employee table.
      static int GetEmployeeCount(string connectionString)
      {
         int result = 0;
         using (SqlConnection sqlConnection =
            new SqlConnection(connectionString))
         {
            SqlCommand sqlCommand = new SqlCommand(
               $"SELECT COUNT(*) FROM [{s_employeeTable}]", sqlConnection);

            sqlConnection.Open();
            try
            {
               result = (int)sqlCommand.ExecuteScalar();
            }
            finally
            {
               sqlConnection.Close();
            }
         }
         return result;
      }

      // Retrieves the ID of the first employee that has the provided name.
      static int GetEmployeeID(string lastName, string firstName,
         string connectionString)
      {
         using (SqlConnection connection =
            new SqlConnection(connectionString))
         {
            SqlCommand command = new SqlCommand(
               $"SELECT TOP (1) [Employee ID] FROM [{s_employeeTable}] " +
               "WHERE [Last Name] = @lastName AND [First Name] = @firstName ORDER BY [Employee ID]",
               connection);

            command.Parameters.Add("@lastName", System.Data.SqlDbType.NVarChar).Value = lastName;
            command.Parameters.Add("@firstName", System.Data.SqlDbType.NVarChar).Value = firstName;

            connection.Open();
            try
            {
               object result = command.ExecuteScalar();
               if (result == null)
                  throw new KeyNotFoundException("No matching employee.");
               return (int)result;
            }
            finally
            {
               connection.Close();
            }
         }
      }

      // Posts random Employee data to the provided target block.
      static void PostRandomEmployees(ITargetBlock<Employee> target, int count)
      {
         Console.WriteLine($"Adding {count} entries to Employee table...");

         for (int i = 0; i < count; i++)
         {
            target.Post(Employee.Random());
         }
      }

      // Adds random employee data to the database by using dataflow.
      static void AddEmployees(string connectionString, int count)
      {
         // Create an ActionBlock<Employee> object that adds a single
         // employee entry to the database.
         var insertEmployee = new ActionBlock<Employee>(e =>
            InsertEmployees(new Employee[] { e }, connectionString));

         // Post several random Employee objects to the dataflow block.
         PostRandomEmployees(insertEmployee, count);

         // Set the dataflow block to the completed state and wait for
         // all insert operations to complete.
         insertEmployee.Complete();
         insertEmployee.Completion.Wait();
      }

      // Adds random employee data to the database by using dataflow.
      // This method is similar to AddEmployees except that it uses batching
      // to add multiple employees to the database at a time.
      static void AddEmployeesBatched(string connectionString, int batchSize,
         int count)
      {
         // Create a BatchBlock<Employee> that holds several Employee objects and
         // then propagates them out as an array.
         var batchEmployees = new BatchBlock<Employee>(batchSize);

         // Create an ActionBlock<Employee[]> object that adds multiple
         // employee entries to the database.
         var insertEmployees = new ActionBlock<Employee[]>(a =>
            InsertEmployees(a, connectionString));

         // Link the batch block to the action block.
         batchEmployees.LinkTo(insertEmployees);

         // When the batch block completes, set the action block also to complete.
         batchEmployees.Completion.ContinueWith(delegate { insertEmployees.Complete(); });

         // Post several random Employee objects to the batch block.
         PostRandomEmployees(batchEmployees, count);

         // Set the batch block to the completed state and wait for
         // all insert operations to complete.
         batchEmployees.Complete();
         insertEmployees.Completion.Wait();
      }

      // Displays information about several random employees to the console.
      static void GetRandomEmployees(string connectionString, int batchSize,
         int count)
      {
         // Create a BatchedJoinBlock<Employee, Exception> object that holds
         // both employee and exception data.
         var selectEmployees = new BatchedJoinBlock<Employee, Exception>(batchSize);

         // Holds the total number of exceptions that occurred.
         int totalErrors = 0;

         // Create an action block that prints employee and error information
         // to the console.
         var printEmployees =
            new ActionBlock<Tuple<IList<Employee>, IList<Exception>>>(data =>
            {
               // Print information about the employees in this batch.
               Console.WriteLine("Received a batch...");
               foreach (Employee e in data.Item1)
               {
                  Console.WriteLine($"Last={e.LastName} First={e.FirstName} ID={e.EmployeeID}");
               }

               // Print the error count for this batch.
               Console.WriteLine($"There were {data.Item2.Count} errors in this batch...");

               // Update total error count.
               totalErrors += data.Item2.Count;
            });

         // Link the batched join block to the action block.
         selectEmployees.LinkTo(printEmployees);

         // When the batched join block completes, set the action block also to complete.
         selectEmployees.Completion.ContinueWith(delegate { printEmployees.Complete(); });

         // Try to retrieve the ID for several random employees.
         Console.WriteLine("Selecting random entries from Employees table...");
         for (int i = 0; i < count; i++)
         {
            try
            {
               // Create a random employee.
               Employee e = Employee.Random();

               // Try to retrieve the ID for the employee from the database.
               e.EmployeeID = GetEmployeeID(e.LastName, e.FirstName, connectionString);

               // Post the Employee object to the Employee target of
               // the batched join block.
               selectEmployees.Target1.Post(e);
            }
            catch (KeyNotFoundException e)
            {
               // GetEmployeeID throws KeyNotFoundException when there is
               // no such employee with the given name. When this happens,
               // post the Exception object to the Exception target of
               // the batched join block.
               selectEmployees.Target2.Post(e);
            }
         }

         // Set the batched join block to the completed state and wait for
         // all retrieval operations to complete.
         selectEmployees.Complete();
         printEmployees.Completion.Wait();

         // Print the total error count.
         Console.WriteLine($"Finished. There were {totalErrors} total errors.");
      }

      static void Main()
      {
         string connectionString = Environment.GetEnvironmentVariable("SQL_CONNECTION_STRING");
         if (string.IsNullOrWhiteSpace(connectionString))
            throw new InvalidOperationException("Set the SQL_CONNECTION_STRING environment variable.");

         // Keep the global temporary table alive while worker connections use it.
         using var keeper = new SqlConnection(connectionString);
         keeper.Open();
         using var setup = new SqlCommand(
            $"CREATE TABLE [{s_employeeTable}] " +
            "([Employee ID] int IDENTITY PRIMARY KEY, " +
            "[Last Name] nvarchar(50) NOT NULL, [First Name] nvarchar(50) NOT NULL)", keeper);
         setup.ExecuteNonQuery();

         try
         {
            Stopwatch stopwatch = new Stopwatch();
            Console.WriteLine("Demonstrating non-batched database insert operations...");
            Console.WriteLine($"Original size of Employee table: {GetEmployeeCount(connectionString)}.");
            stopwatch.Start();
            AddEmployees(connectionString, s_insertCount);
            stopwatch.Stop();
            Console.WriteLine("New size of Employee table: {0}; elapsed insert time: {1} ms.",
               GetEmployeeCount(connectionString), stopwatch.ElapsedMilliseconds);
            Console.WriteLine();

            using var reset = new SqlCommand($"TRUNCATE TABLE [{s_employeeTable}]", keeper);
            reset.ExecuteNonQuery();

            Console.WriteLine("Demonstrating batched database insert operations...");
            Console.WriteLine($"Original size of Employee table: {GetEmployeeCount(connectionString)}.");
            stopwatch.Restart();
            AddEmployeesBatched(connectionString, s_insertBatchSize, s_insertCount);
            stopwatch.Stop();
            Console.WriteLine("New size of Employee table: {0}; elapsed insert time: {1} ms.",
               GetEmployeeCount(connectionString), stopwatch.ElapsedMilliseconds);
            Console.WriteLine();

            reset.ExecuteNonQuery();

            Console.WriteLine("Demonstrating batched join database select operations...");
            AddEmployeesBatched(connectionString, s_insertBatchSize, 16);
            GetRandomEmployees(connectionString, s_insertBatchSize, 10);
         }
         finally
         {
            using var cleanup = new SqlCommand($"DROP TABLE [{s_employeeTable}]", keeper);
            cleanup.ExecuteNonQuery();
         }
      }
   }
}

Imports System.Data
Imports Microsoft.Data.SqlClient
Imports System.Collections.Generic
Imports System.Threading.Tasks.Dataflow


' Demonstrates how to use batched dataflow blocks to improve
' the performance of database operations.
Namespace DataflowBatchDatabase
    Friend Class Program
        ' The number of employees to add to the database.
        ' TODO: Change this value to experiment with different numbers of 
        ' employees to insert into the database.
        Private Shared ReadOnly s_insertCount As Integer = 256

        ' The size of a single batch of employees to add to the database.
        ' TODO: Change this value to experiment with different batch sizes.
        Private Shared ReadOnly s_insertBatchSize As Integer = 96

        Private Shared ReadOnly s_employeeTable As String =
            "##DataflowEmployees_" & Guid.NewGuid().ToString("N")

        ' Describes an employee. Each property maps to a 
        ' column in the sample employee table.
        Private Class Employee
            Public Property EmployeeID() As Integer
            Public Property LastName() As String
            Public Property FirstName() As String

            ' A random number generator that helps tp generate
            ' Employee property values.
            Private Shared ReadOnly s_rand As New Random(42)

            ' Possible random first names.
            Private Shared ReadOnly s_firstNames() As String =
                {"Tom", "Mike", "Ruth", "Bob", "John"}
            ' Possible random last names.
            Private Shared ReadOnly s_lastNames() As String =
                {"Jones", "Smith", "Johnson", "Walker"}

            ' Creates an Employee object that contains random 
            ' property values.
            Public Shared Function Random() As Employee
                Return New Employee With {
                    .EmployeeID = -1,
                    .LastName = s_lastNames(s_rand.Next() Mod s_lastNames.Length),
                    .FirstName = s_firstNames(s_rand.Next() Mod s_firstNames.Length)
                }
            End Function
        End Class

        ' Adds new employee records to the database.
        Private Shared Sub InsertEmployees(ByVal employees() As Employee, ByVal connectionString As String)
            Using connection As New SqlConnection(connectionString)
                Try
                    ' Create the SQL command.
                    Dim command As New SqlCommand($"INSERT INTO [{s_employeeTable}] ([Last Name], [First Name]) VALUES (@lastName, @firstName)", connection)

                    connection.Open()
                    For i As Integer = 0 To employees.Length - 1
                        ' Set parameters.
                        command.Parameters.Clear()
                        command.Parameters.Add("@lastName", SqlDbType.NVarChar).Value = employees(i).LastName
                        command.Parameters.Add("@firstName", SqlDbType.NVarChar).Value = employees(i).FirstName

                        ' Execute the command.
                        command.ExecuteNonQuery()
                    Next i
                Finally
                    connection.Close()
                End Try
            End Using
        End Sub

        ' Retrieves the number of entries in the sample employee table.
        Private Shared Function GetEmployeeCount(ByVal connectionString As String) As Integer
            Dim result As Integer = 0
            Using sqlConnection As New SqlConnection(connectionString)
                Dim sqlCommand As New SqlCommand($"SELECT COUNT(*) FROM [{s_employeeTable}]", sqlConnection)

                sqlConnection.Open()
                Try
                    result = CInt(Fix(sqlCommand.ExecuteScalar()))
                Finally
                    sqlConnection.Close()
                End Try
            End Using
            Return result
        End Function

        ' Retrieves the ID of the first employee that has the provided name.
        Private Shared Function GetEmployeeID(ByVal lastName As String, ByVal firstName As String, ByVal connectionString As String) As Integer
            Using connection As New SqlConnection(connectionString)
                Dim query As String = $"SELECT TOP (1) [Employee ID] FROM [{s_employeeTable}] WHERE [Last Name] = @lastName AND [First Name] = @firstName ORDER BY [Employee ID]"
                Dim command As New SqlCommand(query, connection)
                command.Parameters.Add("@lastName", SqlDbType.NVarChar, 50).Value = lastName
                command.Parameters.Add("@firstName", SqlDbType.NVarChar, 50).Value = firstName

                connection.Open()
                Try
                    Dim result = command.ExecuteScalar()
                    If result Is Nothing Then
                        Throw New KeyNotFoundException("No matching employee.")
                    End If
                    Return CInt(result)
                Finally
                    connection.Close()
                End Try
            End Using
        End Function

        ' Posts random Employee data to the provided target block.
        Private Shared Sub PostRandomEmployees(ByVal target As ITargetBlock(Of Employee), ByVal count As Integer)
            Console.WriteLine("Adding {0} entries to Employee table...", count)

            For i As Integer = 0 To count - 1
                target.Post(Employee.Random())
            Next i
        End Sub

        ' Adds random employee data to the database by using dataflow.
        Private Shared Sub AddEmployees(ByVal connectionString As String, ByVal count As Integer)
            ' Create an ActionBlock<Employee> object that adds a single
            ' employee entry to the database.
            Dim insertEmployee = New ActionBlock(Of Employee)(Sub(e) InsertEmployees(New Employee() {e}, connectionString))

            ' Post several random Employee objects to the dataflow block.
            PostRandomEmployees(insertEmployee, count)

            ' Set the dataflow block to the completed state and wait for 
            ' all insert operations to complete.
            insertEmployee.Complete()
            insertEmployee.Completion.Wait()
        End Sub

        ' Adds random employee data to the database by using dataflow.
        ' This method is similar to AddEmployees except that it uses batching
        ' to add multiple employees to the database at a time.
        Private Shared Sub AddEmployeesBatched(ByVal connectionString As String, ByVal batchSize As Integer, ByVal count As Integer)
            ' Create a BatchBlock<Employee> that holds several Employee objects and
            ' then propagates them out as an array.
            Dim batchEmployees = New BatchBlock(Of Employee)(batchSize)

            ' Create an ActionBlock<Employee[]> object that adds multiple
            ' employee entries to the database.
            Dim insertEmployees = New ActionBlock(Of Employee())(Sub(a) Program.InsertEmployees(a, connectionString))

            ' Link the batch block to the action block.
            batchEmployees.LinkTo(insertEmployees)

            ' When the batch block completes, set the action block also to complete.
            batchEmployees.Completion.ContinueWith(Sub() insertEmployees.Complete())

            ' Post several random Employee objects to the batch block.
            PostRandomEmployees(batchEmployees, count)

            ' Set the batch block to the completed state and wait for 
            ' all insert operations to complete.
            batchEmployees.Complete()
            insertEmployees.Completion.Wait()
        End Sub

        ' Displays information about several random employees to the console.
        Private Shared Sub GetRandomEmployees(ByVal connectionString As String, ByVal batchSize As Integer, ByVal count As Integer)
            ' Create a BatchedJoinBlock<Employee, Exception> object that holds
            ' both employee and exception data.
            Dim selectEmployees = New BatchedJoinBlock(Of Employee, Exception)(batchSize)

            ' Holds the total number of exceptions that occurred.
            Dim totalErrors As Integer = 0

            ' Create an action block that prints employee and error information
            ' to the console.
            Dim printEmployees = New ActionBlock(Of Tuple(Of IList(Of Employee), IList(Of Exception)))(
                Sub(data)
                    ' Print information about the employees in this batch.
                    ' Print the error count for this batch.
                    ' Update total error count.
                    Console.WriteLine("Received a batch...")
                    For Each e As Employee In data.Item1
                        Console.WriteLine("Last={0} First={1} ID={2}", e.LastName, e.FirstName, e.EmployeeID)
                    Next e
                    Console.WriteLine("There were {0} errors in this batch...", data.Item2.Count)
                    totalErrors += data.Item2.Count
                End Sub)

            ' Link the batched join block to the action block.
            selectEmployees.LinkTo(printEmployees)

            ' When the batched join block completes, set the action block also to complete.
            selectEmployees.Completion.ContinueWith(Sub() printEmployees.Complete())

            ' Try to retrieve the ID for several random employees.
            Console.WriteLine("Selecting random entries from Employees table...")
            For i As Integer = 0 To count - 1
                Try
                    ' Create a random employee.
                    Dim e As Employee = Employee.Random()

                    ' Try to retrieve the ID for the employee from the database.
                    e.EmployeeID = GetEmployeeID(e.LastName, e.FirstName, connectionString)

                    ' Post the Employee object to the Employee target of 
                    ' the batched join block.
                    selectEmployees.Target1.Post(e)
                Catch e As KeyNotFoundException
                    ' GetEmployeeID throws KeyNotFoundException when there is
                    ' no such employee with the given name. When this happens,
                    ' post the Exception object to the Exception target of
                    ' the batched join block.
                    selectEmployees.Target2.Post(e)
                End Try
            Next i

            ' Set the batched join block to the completed state and wait for 
            ' all retrieval operations to complete.
            selectEmployees.Complete()
            printEmployees.Completion.Wait()

            ' Print the total error count.
            Console.WriteLine("Finished. There were {0} total errors.", totalErrors)
        End Sub

        Shared Sub Main()
            Dim connectionString = Environment.GetEnvironmentVariable("SQL_CONNECTION_STRING")
            If String.IsNullOrWhiteSpace(connectionString) Then
                Throw New InvalidOperationException("Set the SQL_CONNECTION_STRING environment variable.")
            End If

            ' Keep the global temporary table alive while worker connections use it.
            Using keeper As New SqlConnection(connectionString)
                keeper.Open()
                Using setup As New SqlCommand(
                    $"CREATE TABLE [{s_employeeTable}] " &
                    "([Employee ID] int IDENTITY PRIMARY KEY, " &
                    "[Last Name] nvarchar(50) NOT NULL, [First Name] nvarchar(50) NOT NULL)", keeper)
                    setup.ExecuteNonQuery()
                End Using

                Try
                    Dim stopwatch As New Stopwatch()
                    Console.WriteLine("Demonstrating non-batched database insert operations...")
                    Console.WriteLine("Original size of Employee table: {0}.", GetEmployeeCount(connectionString))
                    stopwatch.Start()
                    AddEmployees(connectionString, s_insertCount)
                    stopwatch.Stop()
                    Console.WriteLine("New size of Employee table: {0}; elapsed insert time: {1} ms.", GetEmployeeCount(connectionString), stopwatch.ElapsedMilliseconds)
                    Console.WriteLine()

                    Using reset As New SqlCommand($"TRUNCATE TABLE [{s_employeeTable}]", keeper)
                        reset.ExecuteNonQuery()
                    End Using

                    Console.WriteLine("Demonstrating batched database insert operations...")
                    Console.WriteLine("Original size of Employee table: {0}.", GetEmployeeCount(connectionString))
                    stopwatch.Restart()
                    AddEmployeesBatched(connectionString, s_insertBatchSize, s_insertCount)
                    stopwatch.Stop()
                    Console.WriteLine("New size of Employee table: {0}; elapsed insert time: {1} ms.", GetEmployeeCount(connectionString), stopwatch.ElapsedMilliseconds)
                    Console.WriteLine()

                    Using reset As New SqlCommand($"TRUNCATE TABLE [{s_employeeTable}]", keeper)
                        reset.ExecuteNonQuery()
                    End Using

                    Console.WriteLine("Demonstrating batched join database select operations...")
                    AddEmployeesBatched(connectionString, s_insertBatchSize, 16)
                    GetRandomEmployees(connectionString, s_insertBatchSize, 10)
                Finally
                    Using cleanup As New SqlCommand($"DROP TABLE [{s_employeeTable}]", keeper)
                        cleanup.ExecuteNonQuery()
                    End Using
                End Try
            End Using
        End Sub
    End Class
End Namespace

Se även