요구를 텍스트 파일로 출력을 쓰기 : cmd.exe를에C#을 실행 여러 cmd.exe를의 명령 동시에
실행 여러 개의 명령을 동시에 시작 시간을 포함하여 C# .NET을 사용하여 하나의 텍스트 파일로 출력을 작성하고 실행 된 명령의 종료 시간
이 코드는 XP와 같은 레거시 OS에서 실행해야하므로 dot net 버전 2.0을 사용하려고합니다. 병렬 및 ConcurrentBag 기능은 .NET 4.5 버전을 받고있다
코드 요약 :
- 모든 명령이 실행되도록 유지하는 문자열 목록을 만들었습니다.
캐릭터 목록을 반복하고 정적 메소드 runCommand (문자열 명령) 반드시 각 명령이 병렬로 별도의 쓰레드로 실행하기 위해 스레드를 사용
을 갖는 클래스 매개 변수로 명령을 전달한다.
문제 :
코드는 잘 실행하지만 출력이 콘솔에 쓰는 모든 명령의 반환과 함께 혼합 도착하고 난 파일에 기록 할 때 같은 문제가 발생할 것이라고 확신합니다! 병렬 + 출력에서 실행되는 모든 명령이 깔끔하게 보이고 섞이지 않도록하는 방법은 무엇입니까? 또한 여러 파일이 같은 파일에 쓰려고하기 때문에 파일에 쓰려고 할 때 오류가 발생합니다.
당신은 병렬 및 ConcurrentBag 작업 할 수
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
public static class Test_Con
{
static string d = null;
public static void runCommand(string command)
{
string starttime;
string endtime;
//* Create your Process
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/c" + command;
starttime = "Started at " + DateTime.Now + "\n";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
//* Set your output and error (asynchronous) handlers
process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
//* Start process and handlers
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
endtime = "Completed at " + DateTime.Now + "\n";
d+= "========================================================================";
d+= starttime + endtime ;
Console.WriteLine(d);
}
static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
//* Do your stuff with the output (write to console/log/StringBuilder)
Console.WriteLine(outLine.Data); //This will keep writing all the command output irrespective
}
}
}
더 나은 당신이 할 수있는 그런 다음에 출력을 추가하고 모든 명령이 완료되면 파일에 사전 내용을 작성, 수집의 몇 가지 유형 (PID 및 문자열의 예에 따라 사전)를 가지고있다. – Gusman
http://stackoverflow.com/a/8055430/366904 –
http://stackoverflow.com/questions/8035029/how-to-write-in-a-single-file-with-multiple-threads –