Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6730945
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T10:28:10+00:00 2026-05-26T10:28:10+00:00

My somewhat data-intensive wp7 app persists data as follows: I maintain a change journal

  • 0

My somewhat data-intensive wp7 app persists data as follows: I maintain a change journal reflecting all user activity, and every couple of seconds, a thread timer spins up a threadpool thread that flushes the change journal to a database inside a transaction. It looks something like this:

When the user exits, I stop the timer, flush the journal on the UI thread (takes no more than a second or two), and dismount the DB.

However, if the worker thread is active when the user exits, I can’t figure out how to react gracefully. The system seems to kill the worker thread, so it never finishes its work and never gives up its lock on the database connection, and the ui thread then attempts to acquire the lock, and is immediately killed by the system. I tried setting a flag on the UI thread requesting the worker to abort, but I think the worker was interrupted before it read the flag. Everything works fine except for this 1 in 100 scenario where some user changes end up not being saved to the db, and I can’t seem to get around this.

Very simplified code below:

private Timer _SweepTimer = new Timer(SweepCallback, null, 5000, 5000);

private volatile bool _BailOut = false;
private void SweepCallback(object state) {
    lock (db) { 
        db.startTransaction();

        foreach(var entry in changeJournal){
            //CRUD entry as appropriate
            if(_BailOut){
                db.rollbackTransaction();
                return;
            }
        }

        db.endTransaction();
        changeJournal.Clear();
    }
}

private void RespondToSystemExit(){
    _BailOut = true; //Set flag for worker to exit

    lock(db){ //In theory, should acquire the lock after the bg thread bails out
        SweepCallback(null);//Flush to db on the UI thread
        db.dismount();//App is now ready to close
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T10:28:11+00:00Added an answer on May 26, 2026 at 10:28 am

    Well, just to close this question, I ended up using a manualresetevent instead of the locking, which is to the best of my understanding a misuse of the manualresetevent, risky and hacky, but its better than nothing.

    I still don’t know why my original code wasn’t working.

    EDIT: For posterity, I’m reposting the code to reproduce this from the MS forums:

    //This is a functioning console app showing the code working as it should. Press "w" and then "i" to start and then interrupt the worker
    using System;
    using System.Threading;
    
    namespace deadlocktest {
        class Program {
            static void Main(string[] args) {
                var tester = new ThreadTest();
                string input = "";
                while (!input.Equals("x")) {
                    input = Console.ReadLine();
    
                    switch (input) {
                        case "w":
                            tester.StartWorker();
                            break;
                        case "i":
                            tester.Interrupt();
                            break;
                        default:
                            return;
                    }
                }
            }
        }
    
        class ThreadTest{
            private Object lockObj = new Object();
            private volatile bool WorkerCancel = false;
    
            public void StartWorker(){
                ThreadPool.QueueUserWorkItem((obj) => {
                    if (Monitor.TryEnter(lockObj)) {
                        try {
                            Log("Worker acquired the lock");
                            for (int x = 0; x < 10; x++) {
                                Thread.Sleep(1200);
                                Log("Worker: tick" + x.ToString());
                                if (WorkerCancel) {
                                    Log("Worker received exit signal, exiting");
                                    WorkerCancel = false;
                                    break;
                                }
                            }
                        } finally {
                            Monitor.Exit(lockObj);
                            Log("Worker released the lock");
                        }
                    } else {
                        Log("Worker failed to acquire lock");
                    }
                });
            }
    
            public void Interrupt() {
                Log("UI thread - Setting interrupt flag");
                WorkerCancel = true;
    
                if (Monitor.TryEnter(lockObj, 5000)) {
                    try {
                        Log("UI thread - successfully acquired lock from worker");
                    } finally {
                        Monitor.Exit(lockObj);
                        Log("UI thread - Released the lock");
                    }
                } else {
                    Log("UI thread - failed to acquire the lock from the worker");
                }
            }
    
            private void Log(string Data) {
                Console.WriteLine(string.Format("{0} - {1}", DateTime.Now.ToString("mm:ss:ffff"), Data));
            }
        }
    }
    

    Here is nearly identical code that fails for WP7, just make a page with two buttons and hook them

    using System;
    using System.Diagnostics;
    using System.Threading;
    using System.Windows;
    using Microsoft.Phone.Controls;
    
    namespace WorkerThreadDemo {
        public partial class MainPage : PhoneApplicationPage {
            public MainPage() {
                InitializeComponent();
            }
    
            private Object lockObj = new Object();
            private volatile bool WorkerCancel = false;
            private void buttonStartWorker_Click(object sender, RoutedEventArgs e) {
                ThreadPool.QueueUserWorkItem((obj) => {
                    if (Monitor.TryEnter(lockObj)) {
                        try {
                            Log("Worker acquired the lock");
                            for (int x = 0; x < 10; x++) {
                                Thread.Sleep(1200);
                                Log("Worker: tick" + x.ToString());
                                if (WorkerCancel) {
                                    Log("Worker received exit signal, exiting");
                                    WorkerCancel = false;
                                    break;
                                }
                            }
                        } finally {
                            Monitor.Exit(lockObj);
                            Log("Worker released the lock");
                        }
                    } else {
                        Log("Worker failed to acquire lock");
                    }
                });
            }
    
            private void Log(string Data) {
                Debug.WriteLine(string.Format("{0} - {1}", DateTime.Now.ToString("mm:ss:ffff"), Data));
            }
    
            private void buttonInterrupt_Click(object sender, RoutedEventArgs e) {
                Log("UI thread - Setting interrupt flag");
                WorkerCancel = true;
    
                //Thread.Sleep(3000); UNCOMMENT ME AND THIS WILL START TO WORK! 
                if (Monitor.TryEnter(lockObj, 5000)) {
                    try {
                        Log("UI thread - successfully acquired lock from worker");
                    } finally {
                        Monitor.Exit(lockObj);
                        Log("UI thread - Released the lock");
                    }
                } else {
                    Log("UI thread - failed to acquire the lock from the worker");
                }
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This somewhat follows on from the question Saving application data to the ipad/iphone Really
how data is generated without user activity has never been quite clear to me.
my question is somewhat conceptual, how is parent process' data shared with child process
I have a somewhat complex data model in my iPad application (an OpenGL drawing
I somewhat manage to get the data & stored in Database & also I
I am somewhat new to WPF and Data Binding, it seems very powerful. I'm
I'm still somewhat new to Java and trying to insert data into a database.
I'm trying to echo data from an SQLdatabase into a table that is somewhat
This will be a somewhat abstract question. I am working on a Data Access
I have a NSOperation that downloads some data using NSURLConnection, it looks somewhat like

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.