对 EF4 实体的并发访问(Parallel + EF4)

发布于 2024-09-24 15:30:21 字数 665 浏览 2 评论 0原文

我目前正在使用 EF4 和 WCF 处理在不同渠道(电子邮件、私人消息、应用程序消息)中传递的数千条消息的调度程序服务。

为了尝试加快消息调度,我尝试使用 Parallels:

Parallel.ForEach(currentMessageList, m =>
{
Processors.DispatcherWrapper.Dispatch(m, m.unfChannels.AgentName, m.unfChannels.AgentParameters);
}
);

我的 Dispatch 方法使用反射来匹配通道配置方法并同时处理每条消息,但是当我进行 SaveChanges 时,我在尝试更新线程内的 EF 对象时遇到了大问题() 到全局实体(在 application_start 上初始化)

问题有多种形式:

  • 空对象引用
  • 列表项 属性是对象关键信息的一部分,无法修改。
  • 底层提供程序在打开时失败。
  • 不允许新事务,因为会话中还有其他线程正在运行。 (如果关闭则强制打开连接)

问题是 EF4 是否是线程安全的来实现这种情况? 我拥有全局实体的方法是最佳解决方案吗?还是我应该对每个任务进行 EF4 初始化?

欢迎任何帮助,我是否已经花了 2 个小时试图找出可能的解决方法。

I'm currently working in a dispatcher service that processes thousands of messages delivered in different channels (email, private message, application message) using EF4 and WCF.

To try to speed up message dispatching i'm trying to use Parallels:

Parallel.ForEach(currentMessageList, m =>
{
Processors.DispatcherWrapper.Dispatch(m, m.unfChannels.AgentName, m.unfChannels.AgentParameters);
}
);

My Dispatch method uses reflection to match channel configuration method and process each message concurrently, but I'm having big problems trying to update EF objects within the threads when i make SaveChanges() to a global entity (it's initialized on application_start)

Problems come in various flavors:

  • Null object references
  • List item The property is part of the object's key information and cannot be modified.
  • The underlying provider failed on Open.
  • New transaction is not allowed because there are other threads running in the session. (after forcing connection open if closed)

The question is if EF4 is thread safe to implement this scenario?
Is my approach of having a global Entities the best solution, or should i make per task EF4 initializations?

Any help is welcome, has i already lost 2 hours trying to figure out a possible workaround.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼泪都笑了 2024-10-01 15:30:21

对并发 WCF 调用使用共享上下文确实是很糟糕的做法。您应该始终为每次调用使用新的上下文。我在此处解释了原因。

Using shared context for concurrent WCF calls is really bad practice. You should always use new context for each call. I explained the reason here.

过潦 2024-10-01 15:30:21

我没有一个很好的答案给你,但当面对类似的问题时,我最终将所有更改添加到静态公共 System.Collections.Concurrent.ConcurrentBag 中,然后在所有线程/任务完成后提交它们。

这是一种妥协,但可能是一个“足够好”的解决方案。

I don't have a great answer for you but when faced with a simmilar problem I ended up adding all my changes to a static common System.Collections.Concurrent.ConcurrentBag and then commiting them after all threads/tasks were finished.

It is a compromise, but may be a "good enough" solution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文