我正在编写某种并行执行各种任务的调度程序。我使用 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