このコードスニペットは、フォームコントロールでリアルタイムコマンド出力を表示する方法を示しています。明確さと正確さのためにそれを洗練しましょう。
改善された説明とコード:
コア機能には、コマンドを非同期に実行し、出力の各行でフォームのテキストボックスを更新することが含まれます。 元のコードの主要な問題は、スレッドの同期の処理にあります。 UIスレッドが更新を完了するまでInvoke
ブロックし、遅延が発生する可能性があります。 BeginInvoke
は、アップデートをキューにし、すぐに返すため、優れています。ただし、ここでもBeginInvoke
でも完全には適していません。 より堅牢なアプローチでは、専用のSynchronizationContext
。
改善されたアプローチとコードの内訳:
非同期コマンドの実行:コマンドの実行は、UIスレッドのブロックを防ぐために非同期でなければなりません。 async
およびawait
。
SynchronizationContext:これにより、コマンド出力がバックグラウンドスレッドから受信された場合でも、UIの更新が正しいスレッドで発生することが保証されます。
エラー処理:コードの実行中に潜在的な例外を優雅に管理するために、コードにエラー処理を含める必要があります。
より記述的な変数名が読み取り可能性を高めます。
この改訂されたコードは、より堅牢で効率的で、読みやすいです。エラーを処理し、非同期操作を使用し、
<code class="language-csharp">private async void btnExecute_Click(object sender, EventArgs e) { // Get currently selected tab page and controls var tabPage = tcExecControl.SelectedTab; var commandTextBox = (TextBox)tabPage.Controls[0]; // Assuming command is in the first control var argumentsTextBox = (TextBox)tabPage.Controls[1]; // Assuming arguments are in the second control var outputTextBox = (TextBox)tabPage.Controls[2]; // Assuming output textbox is the third control string command = commandTextBox.Text; string arguments = argumentsTextBox.Text; try { // Capture the SynchronizationContext for UI thread updates var uiContext = SynchronizationContext.Current; // Asynchronously execute the command await Task.Run(() => { using (var process = new Process()) { process.StartInfo.FileName = command; process.StartInfo.Arguments = arguments; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; // Redirect error stream as well process.Start(); // Read output line by line string line; while ((line = process.StandardOutput.ReadLine()) != null) { // Update the textbox on the UI thread uiContext.Post(_ => outputTextBox.AppendText(line + Environment.NewLine), null); } // Read and display error output (if any) string errorLine; while ((errorLine = process.StandardError.ReadLine()) != null) { uiContext.Post(_ => outputTextBox.AppendText("Error: " + errorLine + Environment.NewLine), null); } process.WaitForExit(); } }); } catch (Exception ex) { outputTextBox.AppendText($"An error occurred: {ex.Message}{Environment.NewLine}"); } }</code>
とSynchronizationContext
を追加することを忘れないでください。 また、コマンドとその引数がフォームのテキストボックスで正しく指定されていることを確認してください。
以上がフォーム コントロールでリアルタイム コマンド出力を表示するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。