循环中的任务以错误(最后)索引作为参数

时间:2015-11-03 01:06:01

标签: c# multithreading task

我遇到了弄清楚Task类的问题,我正试图让Process类的进程运行x次。我尝试使用后台工作程序完成此操作,但是当我运行该过程时,它会在开始第二个过程之前等待第一个完成。

以下是我现在要做的事情:

   ps = new Push(this)
   for (int counter = 1; counter <= maxgroup; counter++){              
         t = Task.Run(() => { ps.runCommand(strBatchPath, counter, username, password, password.getString()); });               
        }

对于我的“推”类这里是我正在调用的方法,

    public void runCommand(string batchfile, int groupnumber, string username, SecureString securePassword, string password)
    {
        formControl.setTextbox(groupnumber.ToString());
        string number = groupnumber.ToString();
        string tmp = "/c c:\\psexec.exe -c @c:\\Computers\\group" + number + ".txt -u MYDOMAINNAME\\" + username + " -p " + password + " -h " + @batchfile;


        Process process = new Process();
        process.StartInfo.WorkingDirectory = @"C:\";
        process.StartInfo.FileName = "cmd";
        formControl.setTextbox(tmp);
        process.StartInfo.Arguments = tmp;
        process.StartInfo.UseShellExecute = false;

            process.StartInfo.RedirectStandardOutput = true;
            process.EnableRaisingEvents = true;
            process.StartInfo.RedirectStandardError = true;                  
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.CreateNoWindow = true;

        //* Read the output (or the error)
        // string output = process.StandardOutput.ReadToEnd();
        process.OutputDataReceived += process_DataReceived;
        process.ErrorDataReceived += process_ErrorReceived;


        process.Start();
        process.BeginOutputReadLine();
        process.BeginErrorReadLine();

        process.WaitForExit();


    }

我的问题是当我循环时(从1到2可以说) 我的第一次迭代计数器= 1 当我通过反击

      ps.runCommand();

计数器从3开始 所以在runCommand函数中, 它调用group3.txt两次,而不是group1.txt,group2.txt

我改了它,现在正在使用async / await

         ps = new Push(this);
            for (int counter = 1; counter <= maxgroup; counter++)
            {

                await Task.Run(() =>  ps.runCommand(strBatchPath, counter, username, password, password.getString()) ); 
    }

这实际上是有效的..有点,它只是一次一个。所以在第一个任务完成后,它会启动第二个任务。我怎样才能使它同时运行两个任务?谢谢你的帮助!!

0 个答案:

没有答案