C# Concurrent Database Access Guide

In C#, you can use Task and the async/await keywords to achieve multithreaded concurrent access to databases. Here is a simple example code:

using System;
using System.Threading.Tasks;
using System.Data.SqlClient;

class Program
{
    static async Task Main(string[] args)
    {
        string connString = "YOUR_CONNECTION_STRING";
        
        // 创建多个并发任务
        Task task1 = AccessDatabase(connString, "Task 1");
        Task task2 = AccessDatabase(connString, "Task 2");
        
        // 等待所有任务完成
        await Task.WhenAll(task1, task2);
        
        Console.WriteLine("All tasks completed!");
    }

    static async Task AccessDatabase(string connString, string taskName)
    {
        using (SqlConnection conn = new SqlConnection(connString))
        {
            await conn.OpenAsync();
            
            // 在此处执行数据库操作
            // 例如:执行查询
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM YourTable", conn))
            {
                using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
                {
                    while (await reader.ReadAsync())
                    {
                        Console.WriteLine($"{taskName} - {reader["Column1"]}");
                    }
                }
            }
        }
    }
}

In the example above, we created two concurrent tasks using the Task and async/await keywords, these tasks will simultaneously access the database and perform query operations. In the AccessDatabase method, we open the database connection, execute the query, and output the results. In the Main method, we use Task.WhenAll method to wait for all tasks to complete. This allows for concurrent multi-threaded access to the database.

bannerAds