在方法完成之前,UI不会更新。 (Xamarin)

我正在开始我的移动开发冒险,已经遇到了问题。 我知道在WPF中我会使用BackgroundWorker来更新UI,但它如何与Android一起使用? 我找到了许多建议但这些都不适合我。 执行rest时,下面的代码不会更改文本,它只是等待并立即执行所有操作,这不是我想要的。

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中使用等待单词。

有很多方法可以做到这一点,但是以示例代码的forms:

 button.Click += (object sender, System.EventArgs e) => { Task.Run(async () => { RunOnUiThread(() => txt.Text = "Connecting..."); await Task.Delay(2500); // Simulate SQL Connection time if (sql.testConnection()) { RunOnUiThread(() => txt.Text = "Connected..."); await Task.Delay(2500); // Simulate SQL Load time //load(); } else RunOnUiThread(() => txt.Text = "SQL Connection error"); }); }; 

仅供参考:有一些很棒的库可以帮助创建被动的用户体验, ReactiveUI位于我的列表的顶部,因为它也是一个MVVM框架……