in my code I am doing an iterate calculation which looks as follows:
/// the iteration calculation function
private void DoCalculationEx(string targetFileSource, int num) {
//first, kill the process TrustMoment.exe if it exists
foreach (var process in Process.GetProcessesByName("TrustMoment"))
{
process.Kill();
}
//Then, write contents to the file using a streamwriter
ExportFile(targetFileSource);
//call the process TrustMoment.exe which uses the file
Process pro = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "TrustMoment.exe";
startInfo.WorkingDirectory = targetDirectory;
pro.StartInfo = startInfo;
pro.Start();
pro.WaitForExit(5000);
//to make sure the process ends, I even sleep the thread
Thread.Sleep(1000);
...
doing other things
}
As in my code, the file is firstly written content, then I will call an exterior exe ( TrustMoment.exe) which will read the contents in the file. during the 1st iteration, the code runs ok, but when it comes to 2nd iteration, I will get error message that The file is used by another process. I am pretty sure that this file is used by TrustMoment.exe so I tried to kill TrustMoment.exe before I write contents into the file. But still I got the error message.
As I cannot see which process used it, I am unsure how to solve this problem. Can anyone help me solving this issue? (maybe by async and await, but I am not familiar with it).
By the way when I add some breakpoint in code, it works ok.
Function ExportFile looks as follows:
private void ExportFile(string targetFileSource)
{
StreamWriter sr = new StreamWriter(targetFileSource);
//basic info
sr.WriteLine(this.sliceNum.ToString() + " " + this.earthquakeRatio.ToString());
//coordinate
for (int i = this.sliceNum; i >= 0; i--)
{
string s0 = string.Format("{0:0.0000}", this.topPoints[i].X);
string s1 = string.Format("{0:0.0000}", this.topPoints[i].Y);
string s2 = string.Format("{0:0.0000}", this.bottomPoints[i].X);
string s3 = string.Format("{0:0.0000}", this.bottomPoints[i].Y);
string s4 = string.Format("{0:0.0000}", this.waterLevelPoints[i].X);
string s5 = string.Format("{0:0.0000}", this.waterLevelPoints[i].Y > this.bottomPoints[i].Y ? waterLevelPoints[i].Y : bottomPoints[i].Y);
//string coordinateStr = string.Join("\t", this.topPoints[i].X, this.topPoints[i].Y,
// this.bottomPoints[i].X, this.bottomPoints[i].Y, this.waterLevelPoints[i].X,
// this.waterLevelPoints[i].Y);
string coordinateStr = string.Join("\t", s0, s1, s2, s3, s4, s5);
sr.WriteLine(coordinateStr);
}
//material
for (int i = this.sliceNum - 1; i >= 0; i--)
{
//save fi in radian
double fi = Math.Tan((Math.PI / 180) * phiArr[i]);
string sf = string.Format("{0:0.0000}", fi);
string matStr = string.Join("\t", sf, this.cArr[i],
this.naturalDensityArr[i], this.satDensityArr[i], this.pphArr[i], this.ppvArr[i]);
sr.WriteLine(matStr);
}
//magicNumber 0.918
sr.WriteLine("0.918");
sr.Close();
}