我正在编写一个Xamarin Android应用程序,我有一个长期运行的本机(Java)进程。我想捕获进程的输出(stdout,stderr)并使用进度更新UI。我下面的代码不起作用。现在它阻止了UI线程。
在不阻止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();
答案 0 :(得分:1)
我想捕获进程的输出(stdout,stderr)并使用进度更新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);