C# 在C控制台应用程序中快速运行ADB外壳命令
我正在尝试运行大量的adb shell命令。基本上,我想启动ADBShell,然后快速连续地运行一系列命令。我可以以某种方式重用流程吗?我只想启动adb shell并在运行时更改命令文本 问题是为每个命令创建一个单独的进程会增加很多进程,最终adb会对我产生影响C# 在C控制台应用程序中快速运行ADB外壳命令,c#,shell,adb,C#,Shell,Adb,我正在尝试运行大量的adb shell命令。基本上,我想启动ADBShell,然后快速连续地运行一系列命令。我可以以某种方式重用流程吗?我只想启动adb shell并在运行时更改命令文本 问题是为每个命令创建一个单独的进程会增加很多进程,最终adb会对我产生影响 static void Main(string[] args) { const string AdbBroadcast = "shell am broadcast <my_cmd>";
static void Main(string[] args)
{
const string AdbBroadcast = "shell am broadcast <my_cmd>";
int broacastIndex = 0;
while(true)
{
Console.WriteLine("Outputting " + broacastIndex);
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "adb";
startInfo.Arguments = AdbBroadcast;
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
Thread.Sleep(250);
broacastIndex++;
}
}
当设备没有响应通过adb通过Process发出的shell命令时,您可以检查设备状态,如下所示:
ProcessStartInfo lcmdInfo1;
lcmdInfo1 = new ProcessStartInfo(" adb.exe ", "get-state");
lcmdInfo1.CreateNoWindow = true;
lcmdInfo1.RedirectStandardOutput = true;
lcmdInfo1.RedirectStandardError = true;
lcmdInfo1.UseShellExecute = false;
Process cmd2 = new Process();
cmd2.StartInfo = lcmdInfo1;
var output = new StringBuilder();
var error = new StringBuilder();
cmd2.OutputDataReceived += (o, ef) => output.Append(ef.Data);
cmd2.ErrorDataReceived += (o, ef) => error.Append(ef.Data);
cmd2.Start();
cmd2.BeginOutputReadLine();
cmd2.BeginErrorReadLine();
cmd2.WaitForExit();
cmd2.Close();
lresulterr1 = error.ToString();
lresult1 = output.ToString();
cmd2.Dispose();
//sometimes there is an issue with a previously issued command that causes the device status to be 'Unknown'. Wait until the device status is 'device'
while (!lresult1.Contains("device"))
{
lcmdInfo1 = new ProcessStartInfo(" adb.exe ", "get-state");
lcmdInfo1.CreateNoWindow = true;
lcmdInfo1.RedirectStandardOutput = true;
lcmdInfo1.RedirectStandardError = true;
lcmdInfo1.UseShellExecute = false;
cmd2 = new Process();
cmd2.StartInfo = lcmdInfo1;
output = new StringBuilder();
error = new StringBuilder();
cmd2.OutputDataReceived += (o, ef) => output.Append(ef.Data);
cmd2.ErrorDataReceived += (o, ef) => error.Append(ef.Data);
cmd2.Start();
cmd2.BeginOutputReadLine();
cmd2.BeginErrorReadLine();
cmd2.WaitForExit();
cmd2.Close();
lresulterr1 = error.ToString();
lresult1 = output.ToString();
cmd2.Dispose();
}
//now your device is ready. Go ahead and fire off the shell commands
我不知道这是否有助于解决您的特定错误,但您应该在“WaitForExit”之后完成处理后,在流程上调用.Dispose。如果此循环有大量迭代,那么在操作系统级别上可能会耗尽进程句柄。处理进程时应释放句柄,以便可以重用。