On Jan 3, 2012, at 1:52 PM, Wally McClure wrote:
> I've been working on this simple use of the Progress Dialog.  I have 
> everything working, and then it hit me that I am not using RunOnUIThread.

In your code, you're using ProgressDialog in two places: the button.Click event 
registration, and in ProgressProcess().

The button.Click event registration is fine, as the Click event will be raised 
on the main (UI) thread, so RunOnUiThread() isn't necessary.

ProgressProcess() is run from the ThreadPool, and thus does require 
RunOnUiThread(), which you're using except in `while (progressDialog.Progress < 
100)`. This is bad, as ProgressDialog.Progress isn't thread safe. You've just 
been lucky using it across threads. (Yet more proof that the current threading 
model is broken, as "just happens to work" is code for "will break in the 
unknowable future when you least want it to.")

See the Java example at: 
http://developer.android.com/reference/android/widget/ProgressBar.html

They get around this by "duplicating" the current progress value in a local 
field (`mProgressStatus`), and referencing that in the loop. Your 
ProgressProcess() should thus be:

        int progress;

        private void ProgressProcess(object state)
        {
                while (progress < 100)
                {
                        ++progress;
                        RunOnUiThread(delegate{
                                        progressDialog.IncrementProgressBy(1);
                        });
                        System.Threading.Thread.Sleep(50);
                }
                RunOnUiThread(delegate {
                                progressDialog.Dismiss();
                });
        }

This way, all access to `progressDialog` is done on the UI thread.

 - Jon

_______________________________________________
Monodroid mailing list
Monodroid@lists.ximian.com

UNSUBSCRIBE INFORMATION:
http://lists.ximian.com/mailman/listinfo/monodroid

Reply via email to