[英]Multithreaded EF using MEF
我正在写某种调度程序,它可以并行执行各种任务。 我将MEF用作IoC容器。 因为我知道共享ObjectContext的静态实例不是一个好主意,所以我决定每个线程有一个实例。 我是这样实现的:
[Export(typeof(IDatabaseFactory))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class DatabaseFactory : IDatabaseFactory
{
[Import]
public IServiceResolver ServiceResolver { get; set; }
[ThreadStatic]
private static IEntityModel _dataContext;
public IEntityModel Get()
{
if (_dataContext == null)
{
Debug.WriteLine("*************************");
Debug.WriteLine(string.Format("Created Context Instance on Thread {0}", Thread.CurrentThread.ManagedThreadId));
Debug.WriteLine("*************************");
}
return _dataContext ?? (_dataContext = ServiceResolver.GetService<IEntityModel>());
}
public void Dispose()
{
Debug.WriteLine("^^^^^^^^Disposing Context^^^^^^^^");
if (_dataContext != null)
{
_dataContext.Dispose();
_dataContext = null;
}
}
}
注意_dataContext字段上的ThreadStatic属性; 此代码失败,并显示以下输出:
*************************
Created Context Instance on Thread 9
*************************
-- Running Main Thread on thread 9
-- Scheduling servicetask of type ActiveDirectorySynchronisationServiceTask on thread 14
-- Scheduling servicetask of type LogCleanerServiceTask on thread 15
-- Scheduling servicetask of type TranscriptParseServiceTask on thread 17
-- Scheduling servicetask of type MailServiceTask on thread 16
*************************
*************************
Created Context Instance on Thread 15
*************************
Created Context Instance on Thread 17
*************************
Created Context Instance on Thread 16
*************************
*************************
随着以下错误消息:
{"The transaction operation cannot be performed because there are pending requests working on this transaction."}
请注意,实际错误并不总是相同的(有时“底层提供程序在打开时失败”等),这使我确信这是一个多线程问题。 但我看不出问题吗?
在ObjectContext的实例之间共享连接吗? 我正在使用EF4.0,SQL Server Express 2008
您需要MARS(多个活动结果集), http://msdn.microsoft.com/zh-cn/library/h32h3abf (v = vs.80) .aspx
EF尝试在可能的情况下共享与SQL的连接,这需要在连接字符串级别启用上述功能。 您只有在同时具有多个活动上下文(多线程应用程序或封闭性差的上下文)时才真正看到此问题。
我找到了解决此问题的方法。 我向ObjectContext类定义添加了[PartCreationPolicy(CreationPolicy.NonShared)]
。 未明确定义此属性,可能使用了共享引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.