![](/img/trans.png)
[英]How to run in parallel a query from synchronous code in C# via Entity Framework
[英]How to run 3 sql query from C# code in parallel
我能够从 C# 代码中一一运行 SQL 查询。 但是如何使用 C# 代码一起运行 3 个 SQL 查询(并行)。
我只想并行运行选择相关的查询。 下面是我在并行中运行选择 SQL 查询的代码。 此代码在 sqlutility 类中:
public static SqlDataReader ExecuteQuery(string query)
{
OpenConnection(); //This will establish connection
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = command.ExecuteReader();
return reader;
}
OpenConnection()
函数将在 DB 中建立连接。 我只是通过将 sql 查询作为参数传递来从我的测试方法中调用这个函数。
我的调用方法是这样的:
SqlUtility.ExecuteQuery(Query1);
SqlUtility.ExecuteQuery(Query2);
SqlUtility.ExecuteQuery(Query3);
每个 SQL 查询需要大约。 5分钟执行时间。 所以执行的总时间是 15 分钟。 通过并行运行 SQL 查询,执行时间将减少到 5 分钟。
如果您想并行运行子任务,但要等待整个操作完成然后继续您的代码,您可以使用Parallel
。 这是一个示例(您必须在其中实施查询)。
var fxList = new List<Action>();
fxList.Add(() =>
{
for(int i = 1; i<= 20; i++)
{
Console.WriteLine($"A{i}");
Thread.Sleep(300);
}
});
fxList.Add(() =>
{
for (int i = 1; i <= 20; i++)
{
Console.WriteLine($"B{i}");
Thread.Sleep(250);
}
});
fxList.Add(() =>
{
for (int i = 1; i <= 20; i++)
{
Console.WriteLine($"C{i}");
Thread.Sleep(450);
}
});
Parallel.ForEach(fxList, (item) => item.Invoke());
Console.WriteLine("-all done-");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.