What is Device.BeginInvokeOnMainThread for?

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).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)