title: SQL Server Compact Edition 4 - AccessViolationException
body: <p>I'm building a .NET 4 WPF application using Entity Framework code first and SQL Server Compact 4.0.  I'm trying to call <code>DbContext.SaveChanges()</code> on a background thread to avoid blocking the UI, but I'm occasionally getting the following exception:</p>
  
  <pre><code>System.AccessViolationException occurred
    Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
    Source=System.Data.SqlServerCe
    StackTrace:
         at System.Data.SqlServerCe.NativeMethodsHelper.OpenStore(IntPtr pOpenInfo, IntPtr pfnOnFlushFailure, IntPtr&amp; pStoreService, IntPtr&amp; pStoreServer, IntPtr&amp; pQpServices, IntPtr&amp; pSeStore, IntPtr&amp; pTx, IntPtr&amp; pQpDatabase, IntPtr&amp; pQpSession, IntPtr&amp; pStoreEvents, IntPtr&amp; pError)
         at System.Data.SqlServerCe.NativeMethods.OpenStore(IntPtr pOpenInfo, IntPtr pfnOnFlushFailure, IntPtr&amp; pStoreService, IntPtr&amp; pStoreServer, IntPtr&amp; pQpServices, IntPtr&amp; pSeStore, IntPtr&amp; pTx, IntPtr&amp; pQpDatabase, IntPtr&amp; pQpSession, IntPtr&amp; pStoreEvents, IntPtr&amp; pError)
         at System.Data.SqlServerCe.SqlCeConnection.Open(Boolean silent)
         at System.Data.SqlServerCe.SqlCeConnection.Open()
         at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean&amp; closeStoreConnectionOnFailure)
         at System.Data.EntityClient.EntityConnection.Open()
         at System.Data.Objects.ObjectContext.EnsureConnection()
         at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
         at System.Data.Entity.Internal.InternalContext.SaveChanges()
         at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
         at System.Data.Entity.DbContext.SaveChanges()
         at SourceLog.Model.LogSubscriptionManager.&lt;SaveChanges&gt;b__2() in C:\github.com\tomhunter-gh\SourceLog\SourceLog.Model\LogSubscriptionManager.cs:line 51
    InnerException: (null)
  </code></pre>
  
  <p>Here's the code that calls <code>SaveChanges()</code>:</p>
  
  <pre><code>internal static readonly object DbSaveLockObject = new object();
  public static void SaveChanges()
  {
      Task.Factory.StartNew(() =&gt;
      {
          lock (DbSaveLockObject)
          {
              Debug.WriteLine(DateTime.Now + ": SaveChanges in lock");
              Db.SaveChanges();
          }
      });
  }
  </code></pre>