UI 不会更新,直到方法使用 Xamarin 完成 [英] UI not updating until method finished using Xamarin
问题描述
我正在开始我的移动开发冒险,但已经遇到了一个问题.我知道在 WPF 中我会使用 BackgroundWorker
来更新 UI,但是它如何与使用 Xamarin 的 Android 一起工作?
I'm starting my adventure with mobile developing and already faced a problem. I know in WPF I would use BackgroundWorker
to update the UI, but how does it work with Android using Xamarin?
我找到了很多建议,但没有一个对我有用.下面的代码在执行其余部分时不会更改文本,它只是等待并立即执行,这不是我想要的.
I've found many advises but none of these worked for me. The code below won't change the text while the rest is being executed, it just awaits and performs all at once, which isn't what I want.
private void Btn_Click(object sender, System.EventArgs e)
{
RunOnUiThread(() => txt.Text = "Connecting...");
//txt.Text = sql.testConnectionWithResult();
if (sql.testConnection())
{
txt.Text = "Connected";
load();
}
else
txt.Text = "SQL Connection error";
}
推荐答案
这里您的操作来自按钮单击操作,因此您无需使用 RunOnUiThread,因为您已准备好处理此操作.
Here your action comes from a button click action, so you don't need to use RunOnUiThread because you are ready working on this one.
如果我正确理解你的代码,它应该是这样的:
If I understand correctly your code it should look like this :
private void Btn_Click(object sender, System.EventArgs e)
{
txt.Text = "Connecting...";
//do your sql call in a new task
Task.Run(() => {
if (sql.testConnection())
{
//text is part of the UI, so you need to run this code in the UI thread
RunOnUiThread((() => txt.Text = "Connected"; );
load();
}
else{
//text is part of the UI, so you need to run this code in the UI thread
RunOnUiThread((() => txt.Text = "SQL Connection error"; );
}
});
}
Task.Run 中的代码将被异步调用而不会阻塞 ui.如果您需要在更新 UI 元素之前等待特定工作,您可以在 Task.Run 中使用 await 字.
The code inside Task.Run will be called asynchronously without blocking the ui. You can use await word inside the Task.Run if you need to wait for specific work before update UI elements.
这篇关于UI 不会更新,直到方法使用 Xamarin 完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!