我正在开始我的移动开发冒险,并且已经遇到了一个问题。我知道在 WPF 中我会使用BackgroundWorker
更新 UI,但它如何使用 Xamarin 与 Android 配合使用?
我找到了很多建议,但没有一个对我有用。下面的代码在执行其余代码时不会更改文本,它只是等待并立即执行所有操作,这不是我想要的。
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,因为您已准备好处理此操作。
如果我正确理解你的代码,它应该是这样的:
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 中使用 wait 字。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)