我正在开发Windows CE和.NET Compact Framework 3.5的应用程序。
代码在调试模式下运行正常,但当我将模式更改为Release时,会出现各种异常。我认为这与编译器尝试在发布模式下实现的一些优化有关,比如过早地处理和垃圾收集对象。
以下方法,尝试将实体插入到Sql Compact数据库中,抛出两个异常(我认为它是随机的):
public int Add<T>(List<T> entities)
{
int rowsEffected = 0;
EntityMetadata metadata = GetMetadata<T>();
using (SqlCeCommand command = new SqlCeCommand())
{
command.Connection = connection;
command.CommandType = CommandType.TableDirect;
command.CommandText = metadata.EntityMapAttribute.TableName;
SqlCeResultSet set = command.ExecuteResultSet(ResultSetOptions.Scrollable | ResultSetOptions.Updatable);
// Get generated Id, used in the loop below
command.CommandType = CommandType.Text;
command.CommandText = "SELECT @@IDENTITY";
foreach (var entity in entities)
{
SqlCeUpdatableRecord record = set.CreateRecord();
PropertyMetadata pkPropertyMetadata = null;
foreach (var prop in metadata.PropertyMetadataList)
{
if (prop.Attribute.IsPK)
{
// Identify PK Property, avoid setting values (db automatically sets id)
pkPropertyMetadata = prop;
}
else
{
object columnValue = prop.GetAccesssorDelegates<T>().Getter(entity);
record.SetValue(prop.Attribute.ColumnNumber, columnValue);
}
}
set.Insert(record);
// Get Id of the inserted entity
if (pkPropertyMetadata != null)
{
object rawid = command.ExecuteScalar();
object convertedId = Convert.ChangeType(rawid, pkPropertyMetadata.Attribute.ColumnType, null);
pkPropertyMetadata.GetAccesssorDelegates<T>().Setter(entity, convertedId);
}
rowsEffected++;
}
return rowsEffected;
}
}
例外1:
Test 'M:Babil04_Mobil.Tests.ORMTests.Engine_Works' failed: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at System.Data.SqlServerCe.NativeMethods.ExecuteQueryPlan(IntPtr pTx, IntPtr pQpServices, IntPtr pQpCommand, IntPtr pQpPlan, IntPtr prgBinding, Int32 cDbBinding, IntPtr pData, Int32& recordsAffected, ResultSetOptions& cursorCapabilities, IntPtr& pSeCursor, Int32& fIsBaseTableCursor, IntPtr pError)
at System.Data.SqlServerCe.SqlCeCommand.ExecuteCommandText(IntPtr& pCursor, Boolean& isBaseTableCursor)
at System.Data.SqlServerCe.SqlCeCommand.ExecuteCommand(CommandBehavior behavior, String method, ResultSetOptions options)
at System.Data.SqlServerCe.SqlCeCommand.ExecuteScalar()
MORMEngine.cs(182,0): at MORM.MORMEngine.Add[T](List`1 entities)
Tests\ORMTests.cs(187,0): at Babil04_Mobil.Tests.ORMTests.Engine_Works()
例外2:
Test 'M:Babil04_Mobil.Tests.ORMTests.Can_Insert_Multiple' failed: Cannot access a disposed object.
Object name: 'SqlCeResultSet'.
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'SqlCeResultSet'.
at System.Data.SqlServerCe.SqlCeResultSet.CreateRecord()
MORMEngine.cs(162,0): at MORM.MORMEngine.Add[T](List`1 entities)
Tests\ORMTests.cs(187,0): at Babil04_Mobil.Tests.ORMTests.Can_Insert_Multiple()
调用抛出异常的方法的单元测试:
[Test]
public void Can_Insert_Multiple()
{
MORMEngine engine = new MORMEngine(connectionString);
engine.OpenConnection();
List<TestInventory> inventories = new List<TestInventory>();
for (int i = 0; i < 10000; i++)
{
inventories.Add(new TestInventory
{
Code = "test" + i
});
}
Stopwatch watch = new Stopwatch();
watch.Start();
int rows = engine.Add<TestInventory>(inventories);
watch.Stop();
Console.WriteLine("Completed in {0} ms.", watch.ElapsedMilliseconds);
Assert.That(rows == 10000);
}
升级说SqlCeResultSet已经处置。我既没有在对象上调用Dispose()
方法,也没有将其设置为null
。为什么要处理?为什么它在调试模式下运行良好但在发布模式下没有运行?
任何想法都会受到赞赏。
答案 0 :(得分:1)
根据我之前的评论 - 似乎在engine
行之后的测试中没有引用int rows = engine.Add<TestInventory>(inventories);
,并且对engine
的唯一引用(通过隐式{{1 this
中的{}}是访问连接的行。在此行之后,没有对引擎的进一步引用,因此在发布模式下,它将符合GC的条件。看来(假设我的建议更正了问题)可能会在某个地方(在您的Add<T>(List<T>)
或其他地方)有一个终结器导致在MORMEngine
仍在运行时处理连接。 (在调试模式下,对象的生命周期会延长,直到它们退出范围,以简化调试,这可能是此问题仅出现在发布模式中的原因)
为确保引擎在Add<>()
的通话过程中保持活动状态,以下方法似乎有效:
Add<>()
或者最好使用...
watch.Start();
int rows = engine.Add<TestInventory>(inventories);
GC.KeepAlive(engine); // Ensure that the engine remains alive until Add completes
watch.Stop();
...
语句明确地处理engine
:
using()