C#实现多线程查询数据库不重复数据
时间: 2023-09-10 16:12:08 浏览: 95
可以使用C#的多线程和数据库查询来实现不重复的数据查询。以下是一个简单的示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Threading;
class Program
{
static HashSet<int> resultSet = new HashSet<int>(); // 用于存储查询结果的集合
static object lockObject = new object(); // 用于线程同步的锁对象
static void Main(string[] args)
{
int numberOfThreads = 5; // 设置线程数量
// 创建并启动多个线程
for (int i = 0; i < numberOfThreads; i++)
{
Thread thread = new Thread(DoDatabaseQuery);
thread.Start();
}
// 等待所有线程完成
while (true)
{
bool allDone = true;
lock (lockObject)
{
if (resultSet.Count < numberOfThreads)
{
allDone = false;
}
}
if (allDone)
{
break;
}
Thread.Sleep(100);
}
// 输出查询结果
foreach (int result in resultSet)
{
Console.WriteLine(result);
}
}
static void DoDatabaseQuery()
{
// 在此处执行数据库查询,并将结果添加到resultSet集合中
// 这里只是一个示例,你需要根据具体情况修改下面的代码
using (SqlConnection connection = new SqlConnection("YourConnectionString"))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT DISTINCT Id FROM YourTable", connection);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int result = reader.GetInt32(0);
lock (lockObject)
{
resultSet.Add(result);
}
}
}
}
}
}
```
上述代码使用了一个 `HashSet<int>` 集合来存储查询结果,以保证结果不重复。同时使用一个 `lockObject` 对象作为锁来实现线程同步,避免多个线程同时修改结果集合。每个线程执行数据库查询,并将查询结果添加到结果集合中。
请注意,你需要将代码中的 `YourConnectionString` 替换为你自己的数据库连接字符串,并根据你的数据库表结构修改查询语句。此外,为了简化代码,我在查询语句中使用了 `DISTINCT` 关键字来确保返回的结果不重复,你可以根据实际需求进行修改。