发布模式下有奇怪的 CLR/编译器行为,但调试模式下则不然

问题描述 投票:0回答:1

我正在开发适用于 Windows CE 和 .NET Compact Framework 3.5 的应用程序。

代码在调试模式下运行良好,但是当我将模式更改为发布模式时,出现各种异常。我认为这与编译器试图在发布模式下实现的一些优化有关,例如过早处置和垃圾收集对象。

以下方法,尝试将实体插入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。我既没有在对象上调用

Dispose()
方法,也没有将其设置为
null
。为什么它会被处置?为什么在 Debug 模式下可以正常运行,但在 Release 模式下就不行?

任何想法将不胜感激。

c# clr compact-framework dispose
1个回答
1
投票

根据我之前的评论 - 似乎在

engine
行之后的测试中没有对
int rows = engine.Add<TestInventory>(inventories);
的引用,并且
engine
中对
this
(通过隐式
Add<T>(List<T>)
)的唯一引用是该行访问连接的位置。在此行之后,不再对引擎进行引用,因此在发布模式下它将有资格进行 GC。看来(鉴于我的建议纠正了问题),某处(在您的
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()

[Test]
public void Can_Insert_Multiple()
{
    using (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);
    }
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.