Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Device.BeginInvokeOnMainThread for?

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.

like image 902
Andres Pabon Aguilar Avatar asked May 22 '17 20:05

Andres Pabon Aguilar


People also ask

What is device BeginInvokeOnMainThread?

If you are running code on a background thread and need to update the UI, BeginInvokeOnMainThread() allows you to force your code to run on the main thread, so you can update the UI. Follow this answer to receive notifications.

What is xamarin essentials?

Xamarin. Essentials provides a single cross-platform API that works with any iOS, Android, or UWP application that can be accessed from shared code no matter how the user interface is created. See the platform & feature support guide for more information on supported operating systems.


1 Answers

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

like image 114
pinedax Avatar answered Sep 19 '22 12:09

pinedax