From c152c6b5a9a45be3b6a7c72fb4142662edd669a2 Mon Sep 17 00:00:00 2001 From: Mitja Felicijan Date: Wed, 24 May 2023 06:41:01 +0200 Subject: Added tags --- content/notes/non-blocking-shell-exec-csharp.md | 43 +++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 content/notes/non-blocking-shell-exec-csharp.md (limited to 'content/notes/non-blocking-shell-exec-csharp.md') diff --git a/content/notes/non-blocking-shell-exec-csharp.md b/content/notes/non-blocking-shell-exec-csharp.md new file mode 100644 index 0000000..4ac3904 --- /dev/null +++ b/content/notes/non-blocking-shell-exec-csharp.md @@ -0,0 +1,43 @@ +--- +title: Execute not blocking async shell command in C# +url: non-blocking-shell-exec-csharp.html +date: 2023-05-24 +type: notes +draft: false +tags: [csharp, async, shell] +--- + +Execute a shell command in async in C# while not blocking the UI thread. + +```c# +private async Task executeCopyCommand() +{ + await Task.Run(() => + { + var processStartInfo = new ProcessStartInfo("cmd", "/c dir") + { + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + + var process = new Process + { + StartInfo = processStartInfo + }; + + process.Start(); + process.WaitForExit(); + }); +} +``` + +Make sure that `async` is present in the function definition and `await` is +used in the method that calls `executeCopyCommand()`. + +```c# +private async void button_Click(object sender, EventArgs e) +{ + await executeCopyCommand(); +} +``` -- cgit v1.2.3