On Jul 23, 2012, at 3:49 PM, JLee wrote:
> I already found the solution (RunOnUIThread), but its import to my, to
> understand, why C#?, Mono?, Android? shows this behaviour.
All three?
Just like WPF and System.Windows.Forms, UI objects in Android may only be
accessed from the UI thread.
ThreadPool threads will _never_ be the UI thread.
Consequently, if you do _anything_ on a non-UI thread, you must marshal the
call back to the UI thread before doing anything to UI objects. (Again, same as
with WinForms and WPF and Gtk# and MonoMac and Swing and...nearly every UI
toolkit for the past 40 years except BeOS, really.)
Which brings us to events: in C#/.NET, events are raised on the thread raising
the event. Thus, if you have:
partial class MyActivity : Activity {
public override void OnCreate(Bundle b)
{
// ...
ThreadPool.QueueUserWorkItem (_ => LoadData ());
}
public event EventHandler MyEvent;
void LoadData ()
{
var h = MyEvent;
if (h != null)
h (this, EventArgs.Empty);
}
}
LoadData() will be invoked on a ThreadPool thread, and thus the
Activity.MyEvent event will be raised on a ThreadPool thread. C# will not do
any thread marshaling for you, nor will the default delegate framework.
(Again, this is also true in WPF and WinForms...)
Java/Android is no different in this regard: neither Java nor Android will do
any implicit marshaling to the UI thread (unless you use AsyncTask/etc.). If
you create a new Thread, you need to marshal to the UI thread.
- Jon
_______________________________________________
Monodroid mailing list
[email protected]
UNSUBSCRIBE INFORMATION:
http://lists.ximian.com/mailman/listinfo/monodroid