As you can see below, I have Parallel.For loop. If run the program while file does not exist , it gives an error like “The process cannot access the file ‘C:\ShowTime Error Logs\logFile.txt’ because it is being used by another process.”
However if file exist there is no error. I’m confused, my code already create the file even if file does not exist. Why it gives me an error if the file does not exist before run the program. And How can I fix it?
Thx
ErrorLog el = new ErrorLog();
Parallel.For(0, 100000, delegate(int i)
{
el.WriteToShowTimeLog("logFile", "", "", (i).ToString(), "", "", @"C:\");
});
ErrorLog class has a function and static variable
private static readonly object lock_ = new object();
public void WriteToShowTimeLog(string fileName, string errorMessage, string description, string movieID, string theaterID, string showTimeDate, string folderPath)
{
string filePath = folderPath + @"\ShowTime Error Logs\" + fileName + ".txt";
lock (lock_)
{
if (!Directory.Exists(folderPath + @"\ShowTime Error Logs"))
{
Directory.CreateDirectory(folderPath + @"\ShowTime Error Logs");
}
if (!File.Exists(filePath))
{
File.Create(filePath);
}
using (StreamWriter dosya = new StreamWriter(filePath,true))
{
dosya.WriteLine("TheaterID: " + theaterID);
dosya.WriteLine("MovieID: " + movieID);
dosya.WriteLine("Show Time Date: " + showTimeDate);
dosya.WriteLine("Hata Mesajı: " + errorMessage);
dosya.WriteLine("Açıklama: " + description);
dosya.WriteLine("Hata Alınan Zaman:" + DateTime.Now);
dosya.WriteLine("-------------------------------------------------------------------------------------------------------");
dosya.Close();
}
}
}
You need to include the file checking and creation in the lock, otherwise you can create it from two separate thread simultaneously, producing the error you see.
EDIT
The
File.Createreturns an open file. Then the StreamWriter tries to open it again. You probably should simple set options for the streamwriter to use rather than trying to create it and then re-create it for the StreamWriter.