What is Device.BeginInvokeOnMainThread for?

Andres Pabon Aguilar picture Andres Pabon Aguilar · May 22, 2017 · Viewed 14.4k times · Source

I would like someone to explain to me what is Device.BeginInvokeOnMainThread and what is it for?

And also some examples of cases where it's used.

Answer

pinedax picture pinedax · May 23, 2017

Just to add an example.

Imagine you have an async method DoAnyWorkAsync if you call it (just as an example) this way:

 DoAnyWorkAsync().ContinueWith ((arg) => {
                StatusLabel.Text = "Async operation completed...";
            });

StatusLabel is a label you have in the XAML.

The code above will not show the message in the label once the async operation had finished, because the callback is in another thread different than the UI thread and because of that it cannot modify the UI.

If the same code you update it a bit, just enclosing the StatusLabel text update within Device.BeginInvokeOnMainThread like this:

 DoAnyWorkAsync().ContinueWith ((arg) => {
     Device.BeginInvokeOnMainThread (() => {
                StatusLabel.Text = "Async operation completed...";
           });
     });

there will not be any problem.

Try it yourself, replacing DoAnyWorkAsync() with Task.Delay(2000).