diff options
| author | Mitja Felicijan <mitja.felicijan@gmail.com> | 2024-03-10 14:59:14 +0100 |
|---|---|---|
| committer | Mitja Felicijan <mitja.felicijan@gmail.com> | 2024-03-10 14:59:14 +0100 |
| commit | 1100562e29f6476448b656dbddd4cf22505523f6 (patch) | |
| tree | 442eec492199104bd49dfd74474ce89ade8fcac9 /content/notes/2023-05-22-non-blocking-shell-exec-csharp.md | |
| parent | a40d80be378e46a6c490e1b99b0d8f4acd968503 (diff) | |
| download | mitjafelicijan.com-1100562e29f6476448b656dbddd4cf22505523f6.tar.gz | |
Move back to JBMAFP
Diffstat (limited to 'content/notes/2023-05-22-non-blocking-shell-exec-csharp.md')
| -rw-r--r-- | content/notes/2023-05-22-non-blocking-shell-exec-csharp.md | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/content/notes/2023-05-22-non-blocking-shell-exec-csharp.md b/content/notes/2023-05-22-non-blocking-shell-exec-csharp.md new file mode 100644 index 0000000..afe7491 --- /dev/null +++ b/content/notes/2023-05-22-non-blocking-shell-exec-csharp.md | |||
| @@ -0,0 +1,43 @@ | |||
| 1 | --- | ||
| 2 | title: Execute not blocking async shell command in C# | ||
| 3 | url: /non-blocking-shell-exec-csharp.html | ||
| 4 | date: 2023-05-22T12:00:00+02:00 | ||
| 5 | type: note | ||
| 6 | draft: false | ||
| 7 | --- | ||
| 8 | |||
| 9 | Execute a shell command in async in C# while not blocking the UI thread. | ||
| 10 | |||
| 11 | ```c# | ||
| 12 | private async Task executeCopyCommand() | ||
| 13 | { | ||
| 14 | await Task.Run(() => | ||
| 15 | { | ||
| 16 | var processStartInfo = new ProcessStartInfo("cmd", "/c dir") | ||
| 17 | { | ||
| 18 | RedirectStandardOutput = true, | ||
| 19 | UseShellExecute = false, | ||
| 20 | CreateNoWindow = true | ||
| 21 | }; | ||
| 22 | |||
| 23 | var process = new Process | ||
| 24 | { | ||
| 25 | StartInfo = processStartInfo | ||
| 26 | }; | ||
| 27 | |||
| 28 | process.Start(); | ||
| 29 | process.WaitForExit(); | ||
| 30 | }); | ||
| 31 | } | ||
| 32 | ``` | ||
| 33 | |||
| 34 | Make sure that `async` is present in the function definition and `await` is used | ||
| 35 | in the method that calls `executeCopyCommand()`. | ||
| 36 | |||
| 37 | ```c# | ||
| 38 | private async void button_Click(object sender, EventArgs e) | ||
| 39 | { | ||
| 40 | await executeCopyCommand(); | ||
| 41 | } | ||
| 42 | ``` | ||
| 43 | |||
