2016-10-05 26 views
0

我开始我的冒险与移动开发,并已面临一个问题。我知道在WPF中我会使用BackgroundWorker来更新UI,但它如何与Android一起工作?我发现了很多建议,但这些都不适合我。下面的代码在执行休息时不会改变文本,它只是等待并一次执行,这不是我想要的。直到方法完成才更新UI。 (Xamarin)

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"; 
    } 
+0

我建议一般来看ReactiveUI,它会帮你解决这个问题,再加上它会强制你使用MVVM而不是在按钮事件处理程序中编写逻辑。 –

回答

3

这里你的行动来自于一个按钮点击动作,这样你就不需要使用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内部的等待词。

0

有很多方法可以做到这一点,但在你的例子代码的形式:

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"); 
    }); 
}; 

FYI:有一些伟大的图书馆,可以帮助产生反应的用户体验,与ReactiveUI存在在我的列表顶部,因为它是一个MVVM框架...

+0

为什么“Task.Run(async()=>”?它不需要,因为它没有给“await”带来好处 – Gabsch

+0

但是有了一个异步事件处理程序(反应式必须支持这个,但我不知道),你不需要。新的任务等待只会在那里等候,直到Task.Delay回报 – Gabsch

+0

所以这是不可能的 btnAccept.Click + =(对象发件人,发送System.EventArgs)异步()=> { 等待 一些; }? ; – Gabsch

相关问题