2016-12-24 39 views
0

我正在編寫一個Xamarin Android應用程序,並且我有一個長時間運行的本地(Java)進程。我想捕獲進程的輸出(stdout,stderr)並用進度更新UI。我下面的代碼不起作用。現在它阻止了UI線程。Xamarin:從長時間運行的本機進程更新用戶界面

更新UI而不阻塞UI線程的正確方法是什麼?

string[] myCmd = { "unix_cmd", "--args" }; 

process = Runtime.GetRuntime().Exec(myCmd); 
BufferedReader bufferedStdoutReader = new BufferedReader(new InputStreamReader(process.InputStream)); 
BufferedReader bufferedStderrReader = new BufferedReader(new InputStreamReader(process.ErrorStream)); 

logView.Text += "Stdout >>>>>>>>" + System.Environment.NewLine; 
var txt=""; 
txt = bufferedStdoutReader.ReadLine(); 
while (txt != null) 
{ 
    logView.Text += txt + System.Environment.NewLine; 
    txt = bufferedStdoutReader.ReadLine(); 
} 
logView.Text += "Stdout <<<<<<<<<" + System.Environment.NewLine + System.Environment.NewLine; 

logView.Text += "Stderr >>>>>>>>>>" + System.Environment.NewLine; 
txt = bufferedStderrReader.ReadLine(); 
while (txt != null) 
{ 
    logView.Text += txt + System.Environment.NewLine; 
    txt = bufferedStderrReader.ReadLine(); 
} 
logView.Text += "Stderr <<<<<<<<<<" + System.Environment.NewLine; 

process.WaitFor(); 

回答

1

我想捕捉的過程(標準輸出,標準錯誤)的輸出,並更新與進步的UI。

我想你可以嘗試包裝你的代碼捕獲過程的輸出到一個任務,例如:

public Task<CapturOutputResult> CapturOutput(string) { 
    return Task.Run(delegate { 
     ... 
     return result; 
    }); 
} 

,然後執行這樣的任務:

var result = await CapturOutput(string); 

並最終在UI線程中更新您的UI,例如:

Application.SynchronizationContext.Post(_ => {/* invoked on UI thread */}, null); 
+2

Better Ac tivity.RunOnUiThread(()=> /*....*/); – XTL

+0

Activity.RunOnUiThread是否替換ApplicationSynchronizationContext.Post調用? – Rick

+0

@瑞克,是的,可以被替換。 –

相關問題