ADO.NET调用的并行性 [英] Parallelism on a ADO.NET call

查看:91
本文介绍了ADO.NET调用的并行性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,在SQL Server 2014上调用存储过程。

我填充 DataTable 对象,结果为存储过程。

这是在基类中完成的,在填充之后,它在上运行了一个 Parallel.ForEach() code>数据表。在那个虚拟过程中(每个实体覆盖基础中的方法以填充它的实体类),数据get被设置为 List< 实体的> 。当 Parallel.ForEach()完成后,我调用一个虚拟方法,实体也会覆盖它。这标志着数据加载的结束和 LIST<> ; 在缓存中设置。但是我有时会看到 List<> 中的某些实体是 NULL 。怎么可能?我错过了将所有行设置为正确的值?



我尝试了什么:



我尝试过带有和不带选项的Parallel.ForEach。其中一个选项设置了1个记录的同时加载最大值(实际上是基于行的处理)。

当我使用常规foreach时,我没有看到这种行为。

I have a project in which a stored procedure is Called on a SQL Server 2014.
I fill a DataTable object with the result of the stored procedure.
This is call is done in a base class and after the fill it is running a Parallel.ForEach() on the DataTable. In that virtual proces (each entity overrides the method in base to fill it's entity classes) the data get's set to the entities in a List<Entity>. When the Parallel.ForEach() is finished I call a virtual method which the entity also overrides This marks the end of the dataloading and the LIST<> is set in cache. However I sometimes see that some of Entities in the List<> are NULL. How is that possible? What am I missing to have all the rows set to their proper values?

What I have tried:

I have tried Parallel.ForEach with and without options. One of the options set the simultanious load maximum of 1 record (in fact row based processing).
When I use a regular foreach I do not see this behaviour.

推荐答案

如果你看一下List< T>文档 - List< t>类,MSDN [ ^ ]

你会在底部找到这个:

If you look at the List<T> documentation - List<t> Class, MSDN[^]
You will find this at the bottom:
Quote:

对List< t>执行多个读取操作是安全的,但如果在读取集合时修改了集合,则会出现问题。要确保线程安全,请在读取或写入操作期间锁定集合。要使多个线程可以访问集合以进行读写,您必须实现自己的同步。对于具有内置同步的集合,请参阅System.Collections.Concurrent命名空间中的类。对于固有的线程安全替代方案,请参阅ImmutableList< t>。 class。

It is safe to perform multiple read operations on a List<t>, but issues can occur if the collection is modified while it’s being read. To ensure thread safety, lock the collection during a read or write operation. To enable a collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization. For collections with built-in synchronization, see the classes in the System.Collections.Concurrent namespace. For an inherently thread–safe alternative, see the ImmutableList<t> class.



如果你没有在Parallel.ForEach中实现锁定,你会得到不可预测的行为。


If you do not implement locking inside the Parallel.ForEach, you will get unpredictable behaviour.


这篇关于ADO.NET调用的并行性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆