【问题标题】:Mahapps ProgressRing WPF C#Mahapps ProgressRing WPF C#
【发布时间】:2017-04-19 04:26:04
【问题描述】:

我试图在 cmd 上执行命令时激活进度环,在命令执行时按钮保持按下状态,并在进程完成时释放,但是当进程仍在运行时我无法激活进度环,看起来像WaitForExit 对我不起作用。

 private void Button_Click(object sender, RoutedEventArgs e)
    {

        if (ComboBox.Text == "")
        {
            MessageBox.Show("Select a drive");
        }
        else
        {   
            try
            {
                ProgressRing.IsActive=true;
                Process cmd = new Process();
                cmd.StartInfo.FileName = "cmd.exe";
                cmd.StartInfo.RedirectStandardInput = true;
                cmd.StartInfo.RedirectStandardOutput = true;
                cmd.StartInfo.CreateNoWindow = true;
                cmd.StartInfo.UseShellExecute = false;
                cmd.Start();
                cmd.StandardInput.WriteLine("attrib -r -s -h " + ComboBox.Text + "*.* /s /d");
                cmd.StandardInput.Flush();
                cmd.StandardInput.Close();       
                cmd.WaitForExit();
                ProgressRing.IsActive=false;
            }
            catch (Exception i)
            {
                Console.WriteLine("{0} Exception caught.", i);
                MessageBox.Show("Error");
            }
        }
    }

【问题讨论】:

    标签: c# wpf xaml windows-applications


    【解决方案1】:

    您应该在后台线程上调用阻塞WaitForExit 方法。 UI 线程不能同时显示您的ProgressRing 并等待进程完成。试试这个:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (ComboBox.Text == "")
        {
            MessageBox.Show("Select a drive");
        }
        else
        {
            ProgressRing.IsActive = true;
            string text = ComboBox.Text;
            Task.Factory.StartNew(() =>
            {
                Process cmd = new Process();
                cmd.StartInfo.FileName = "cmd.exe";
                cmd.StartInfo.RedirectStandardInput = true;
                cmd.StartInfo.RedirectStandardOutput = true;
                cmd.StartInfo.CreateNoWindow = true;
                cmd.StartInfo.UseShellExecute = false;
                cmd.Start();
                cmd.StandardInput.WriteLine("attrib -r -s -h " + text + "*.* /s /d");
                cmd.StandardInput.Flush();
                cmd.StandardInput.Close();
                cmd.WaitForExit();
            }).ContinueWith(task =>
            {
                ProgressRing.IsActive = false;
                if (task.IsFaulted)
                {
                    Console.WriteLine("{0} Exception caught.", task.Exception);
                    MessageBox.Show("Error");
                }
            }, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多