Forum Xamarin Cross Platform with Xamarin

Dispatcher.BeginInvoke() Question

Hello Everyone,

Let me begin by saying how thankful I am to be apart of this community, I am really enjoying Xamarin!

I have a quick question. I am messing around in Monogame trying to read Accelerometer data by following the tutorial code listed below.
void accelerometer_CurrentValueChanged(object sender, SensorReadingEventArgs e)
// Call UpdateUI on the UI thread and pass the AccelerometerReading.
Dispatcher.BeginInvoke(() => UpdateUI(e.SensorReading));

As you can see from the code they used a dispatcher to return the changes to the UI thread. After looking around in the classes I have I realized that I cannot locate the dispatcher class.

After digging some more I realized that people have suggested to use platform specific classes to return code to the UI thread. The project I am currently writing is a shared Monogame implementation. Is there a way to do this without being platform specific, and if it has to be how is this handled in Xamarin? I am still new to this whole sharing code routine so any insight would be awesome!

Thanks in advance,


  • ylemsoulylemsoul RUMember ✭✭✭
    edited August 2015

    If you do Xamarin.Forms application then you can use Device.BeginInvokeOnMainThread(). If not and you don't want to write platform-specific dispatching for each project then you can use more portable version with SyncronizationContext:

    1) in the UI thread capture SynchronizationContext:
    this.context = SynchronizationContext.Current

    2) in the thread pool thread:
    void accelerometer_CurrentValueChanged(object sender, SensorReadingEventArgs e) { this.context.Post(state => UpdateUI(((SensorReadingEventArgs)state).SensorReading), e); // post delegate call to the UI thread }

Sign In or Register to comment.