What is Device.BeginInvokeOnMainThread for?

前端 未结 3 1540
無奈伤痛
無奈伤痛 2021-02-01 16:26

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.

3条回答
  •  情书的邮戳
    2021-02-01 16:33

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

提交回复
热议问题