Device.BeginInvokeOnMainThread的作用是什么? [英] What is Device.BeginInvokeOnMainThread for?
问题描述
我希望有人向我解释什么是Device.BeginInvokeOnMainThread,它的作用是什么?
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.
推荐答案
只需添加示例.
假设您有一个异步方法DoAnyWorkAsync
,如果您以这种方式调用它(仅作为示例):
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
是XAML中的标签.
StatusLabel
is a label you have in the XAML.
异步操作完成后,上面的代码将不会在标签中显示该消息,因为回调位于与UI线程不同的另一个线程中,因此该回调无法修改UI.
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.
如果您更新了相同的代码,只需将StatusLabel
文本更新包含在Device.BeginInvokeOnMainThread
中,如下所示:
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...";
});
});
不会有任何问题.
亲自尝试,将DoAnyWorkAsync()
替换为Task.Delay(2000)
.
这篇关于Device.BeginInvokeOnMainThread的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!