Windows Phone has been here for quite a long time. Tons of apps have been developed and more are in process. One of the most common item used is local databases (SDF's). While developing on these we often land up on "InvalidOperationException" while submitting data to local database. We often scramble to find cause for it but looking at the posts we tend to get lost.



Why this exception occurs?

The reason that I observe is that when multiple threads try to access an object (SDF nothing but a file) and try to gain access, results into this exception being thrown. This typically happens when you spawn multiple tasks trying to access a database at same time.

Solution:

Create a class that accepts a Action or Func delegate pass your database access statements as anonymous functions to it. Wrap the execution of your statement under lock statement. The advantage of this approach is that you can use power of captured variables. Simple

public class QueryExecutor

{

     private static object _mylock = new object();

     public static void ExecuteQuery(Action queryAction) 

     {

           lock(_mylock) 

           {

                queryAction();

           }

     }

}

Usage:



Wrap your database calls as

QueryExecutor.ExecuteQuery(() => {using(DBContext......}});

See Also

Another important place to find a huge amount of Windows Phone related articles is the TechNet Wiki itself. The best entry point is Windows Phone Resources on the TechNet Wiki.