大佬教程收集整理的这篇文章主要介绍了在不达到最大 SQL Server 连接的情况下将 Entity Framework Core 与 ThreadPool 一起使用 Parallel.ForEachTask.WhenAll,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我尝试在未达到最大连接数的情况下向我的 sql Server 插入大量数据。
我已经尝试在我的连接字符串中最大化池大小,如下所示:
optionsBuilder.UsesqlServer(@"Server=(localdb)\mssqllocaldb;Database=Echo;Max Pool Size=5000;Pooling=True;");
是否可以为每个线程使用一个连接?
这是我的代码
public static voID GenerateMerIDIEn()
{
List<Parallele> paralleleList = null;
using (var context = new EchoContext())
{
paralleleList = context.Paralleles.ToList();
}
foreach (Parallele parallele in paralleleList)
{
ThreadPool.QueueUserWorkItem(new WaitCallBACk(MerIDIEnTaskCallBACk),parallelE);
}
}
private static voID MerIDIEnTaskCallBACk(object paralleLeobj)
{
Parallele parallele = (ParallelE)paralleLeobj;
// The context always reaches maximum connection because the garbage collector is not fast enough
using (var context = new EchoContext())
{
List<Square> squareList = SquareLogic.GenerateSquare(parallelE);
context.Squares.AddRange(squareList);
context.SaveChanges();
Console.Write("*");
}
}
每次计算后都需要保存吗?可以并行计算然后保存吗?
List<Parallele> paralleleList = null;
using (var context = new EchoContext())
{
paralleleList = context.Paralleles.ToList();
}
List<Square> squares = DoAllWorkInParallel(paralleleList);
// Save once:
using (var context = new EchoContext())
{
context.Squares.AddRange(squares);
context.SaveChanges();
}
我认为您应该将 Parallel.ForEach
与 @H_198_7@maxDegreeOfParallelism 一起使用或使用 Task.WhenAll
。
例如:
public static async Task GenerateMeridien()
{
List<Parallele> paralleleList = null;
using (var context = new EchoContext())
{
paralleleList = context.Paralleles.ToList();
}
Parallel.ForEach(
source: paralleleList,parallelOptions: new ParallelOptions{MaxDegreeOfParallelism = x},body: parallele => Work(parallelE));
}
private static void Work(Parallele parallelE)
{
using (var context = new EchoContext())
{
List<Square> squareList = SquareLogic.GenerateSquare(parallelE);
context.Squares.AddRange(squareList);
await context.SaveChanges();
}
}
public static async Task GenerateMeridien()
{
List<Parallele> paralleleList = null;
using (var context = new EchoContext())
{
paralleleList = context.Paralleles.ToList();
}
var tasks = new List<Task>();
foreach (Parallele parallele in paralleleList)
{
tasks.Add(WorkAsync(parallelE));
}
await Task.WhenAll(tasks.ToArray());
}
private static async Task WorkAsync(Parallele parallelE)
{
using (var context = new EchoContext())
{
List<Square> squareList = SquareLogic.GenerateSquare(parallelE);
context.Squares.AddRange(squareList);
await context.SaveChangesAsync();
}
}
以上是大佬教程为你收集整理的在不达到最大 SQL Server 连接的情况下将 Entity Framework Core 与 ThreadPool 一起使用 Parallel.ForEachTask.WhenAll全部内容,希望文章能够帮你解决在不达到最大 SQL Server 连接的情况下将 Entity Framework Core 与 ThreadPool 一起使用 Parallel.ForEachTask.WhenAll所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。