art*_*rti 2 c# user-interface android task xamarin
我正在开始我的移动开发冒险,并且已经遇到了一个问题。我知道在 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";
}
Run Code Online (Sandbox Code Playgroud)
此处您的操作来自按钮单击操作,因此您无需使用 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"; );
}
});
}
Run Code Online (Sandbox Code Playgroud)
Task.Run 中的代码将被异步调用而不会阻塞 ui。如果您需要在更新 UI 元素之前等待特定工作,您可以在 Task.Run 中使用 await 字。
| 归档时间: |
|
| 查看次数: |
2498 次 |
| 最近记录: |