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.
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.
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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With