Invalid cross-thread access when importing new entities

Mar 8, 2011 at 3:10 PM

I have an offline app that serializes my entities to iso storage. I have 2 methods that serialize and deserialize each entity set in the domain context. I run these in a separate thread.

If I deal with just data already in the database everything works. I can serialize, restart the app, and deserialize.

If I add a new entity it will serialize, but when I restart and begin to deserialize I get an "invalid cross-thread access" exception when the import method tries to add that "new" entity. Specifically here in the import extension:


else if (currentStateSet.ModifiedState != null)
    collection.Add(newEntity); // EXCEPTION HERE


It is before the state is applied so I don't understand what could possibly cause it.

I did try running the serialize and deserialize methods on the UI thread and it would import the "new" entities with no problem. I can't have the long hang times though.

I though maybe it was due to having a UI property bound to the entity set which the new entity was getting added to, but I tried without that code and get the same result.

Any idea of what could be causing this?

Mar 8, 2011 at 4:15 PM

When you say you are getting an exception there, is it actually failing in your code or is it just Visual Studio doing a "break on exception"? If you aren't debugging, is the code actually failing?

Mar 8, 2011 at 4:56 PM

It is failing.

My method is importing the entity sets in a certain order, and it will only successfully import everything before the entity set containing the new entity.

Nov 1, 2011 at 9:26 PM
Edited Nov 1, 2011 at 9:37 PM

The complete stack trace of the exception will help here.

This can usually be resolved by wrapping the offending call with "Dispatcher.BeginInvoke(() => { ... });" so that it will run on the ui thread.

For example, my silverlight application had bound MyDataDomainContext.HasChanges on the ui and so if I made changes to the domain context in a background\worker thread, then I would get the same exception.