在 Windows 10 和 PowerShell 命令行中使用 C# Winforms 会使应用程序永远等待。没有错误只是挂起。怎么解决?

问题描述 投票:0回答:1
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            try
            {
                button1.Enabled = false;

                await RunPowerShellAsync();
                await RunFfmpegAsync();
                button1.Enabled = true;
                MessageBox.Show("GIF creation complete!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"An error occurred: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private Task RunPowerShellAsync()
        {
            return Task.Run(() =>
            {
                string powershellScript = "Get-ChildItem 'D:\\New folder (76)\\Image*.png' | ForEach-Object { \"file '$($_.FullName)'\" } > image_list.txt";
                ProcessStartInfo psi = new ProcessStartInfo
                {
                    FileName = "powershell.exe",
                    Arguments = $"-Command \"{powershellScript}\"",
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true
                };

                using (Process process = new Process { StartInfo = psi })
                {
                    process.Start();
                    process.WaitForExit();
                }
            });
        }

即将到达

WaitForExit
,但在那之后,什么也没有发生 - 它永远不会结束。

c# powershell winforms
1个回答
0
投票

“它永远不会完成”,因为 WaitForExit 等待 powershell 关闭。

在命令中添加 exit,例如:

Get-ChildItem 'D:\\New folder (76)\\Image*.png' | ForEach-Object { \"file '$($_.FullName)'\" } > image_list.txt; exit

应该这样做

© www.soinside.com 2019 - 2024. All rights reserved.