2017-10-22 1 views
-1

다음 명령을 시작하기 전에 각 명령이 완료되기를 기다리는 명령을 세 개 있습니다.다음 명령을 시작하기 전에 각 명령이 완료되기를 기다리는 여러 명령을 어떻게 실행할 수 있습니까?

첫 번째 작업을 완료 한 후 내 구현을 기반으로하지만 두 번째 작업은 시작되지만 backgroundWorker1_RunWorkerCompleted는 전혀 발생시키지 않습니다.

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Diagnostics; 
using System.Drawing; 
using System.IO; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace cmd_commands 
{ 
    public partial class Form1 : Form 
    { 
     string[] commands = new string[] { 
     @"test", 
     @"test1", 
     @"test2" }; 

     int command = 0; 

     public Form1() 
     { 
      InitializeComponent(); 
     } 

     public void runCmd(string command) 
     { 
      ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe"); 
      cmdsi.Arguments = command; 
      Process cmd = Process.Start(cmdsi); 
      cmd.WaitForExit(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

     } 

     private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
     { 
      runCmd(commands[command]); 
      backgroundWorker1.ReportProgress(0, command); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      backgroundWorker1.RunWorkerAsync(); 
     } 

     private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) 
     { 
      label1.Text = "Working on command number: " + e.UserState.ToString(); 
     } 

     private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
     { 
      command++; 
      runCmd(commands[command]); 
     } 
    } 
} 
+1

내 답변이 도움이 되었습니까? –

+0

더 많은 정보가 없다면 결국 충돌 할 것입니다. runCmd (commands [command]). – DonBoitnott

+0

도움이됩니다. https://stackoverflow.com/questions/1728099/visual-c-sharp-gui-stops-responding-when-process-waitforexit-is-used – DonBoitnott

답변

0

BackgroundWorker는 한 번만 상태가 완료되면 다시 시작하지 않으므로 다시 인스턴스화해야합니다.

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
{ 
    command++; 

    if (command < commands.Length) 
    { 
     backgroundWorker1 = new BackgroundWorker(); 
     backgroundWorker1.DoWork += this.backgroundWorker1_DoWork; 
     backgroundWorker1.ProgressChanged += this.backgroundWorker1_ProgressChanged; 
     backgroundWorker1.RunWorkerCompleted += this.backgroundWorker1_RunWorkerCompleted; 
     backgroundWorker1.RunWorkerAsync(); 
    } 
} 
+0

알겠습니다. 내 질문은 어떻게 확인합니까?/명령 프롬프트 명령이 종료되었을 때 알 수 있습니다. 나는 dowork에서하고있다 : cmd.WaitForExit(); 그러나 첫 번째 명령의 프로세스가 아직 끝나지 않은 동안 백그라운드 작업자가 다시 시작하여 다음 명령을 실행하지 못하도록하는 것은 무엇입니까? –

+0

cmd.WaitForExit()이 실행 된 후 명령 프롬프트가 다음 명령을 종료하면. 예 경우에는 아무것도 없으므로 backgroundWorker1_ProgressChanged 및 backgroundWorker1_RunWorkerCompleted 인 다른 이벤트로 이동합니다. –

관련 문제