Reputation: 927
I'm writing a Xamarin Android app and I have a long running native (Java) process. I want to capture the output of the process (stdout, stderr) and update the UI with the progress. The code I have below doesn't work. Right now it blocks the UI thread.
What is the right way to update the UI without blocking the UI thread?
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();
Upvotes: 0
Views: 280
Reputation: 16652
I want to capture the output of the process (stdout, stderr) and update the UI with the progress.
I think you can try to wrap your code for capturing the output of the process into a task for example:
public Task<CapturOutputResult> CapturOutput(string) {
return Task.Run(delegate {
...
return result;
});
}
and then execute the task like this:
var result = await CapturOutput(string);
and finally update your UI in UI thread for example:
Application.SynchronizationContext.Post(_ => {/* invoked on UI thread */}, null);
Upvotes: 1