I am downloading Images from the web using a foreach and tasks, and saving them locally. After doing this I then write to a log saying the file name downloaded etc. The problem is I foresee that two tasks may try to write to the log at the same time causing an error. I would like to be able to lock the Log if any other Task is writing to it but I'm not sure how? So far I have:
int filesDownloaded = 0;
foreach (var fileName in ListOfFileNames)
{
Task.Factory.StartNew(() =>
{
//Download File
}
lock (thislock)
{
Log.WriteLine(string.Format("Downloaded File: {0}", f.FullName), Log.Status.Success);
}
filesDownloaded++;
}
Do I need to lock the filesDownloaded
variable, or as this is a simple ++ operation does it not matter?
EDIT
Static Log Class:
public enum Status
{
Info,
Error,
Success
}
private static string Directory { get; set; }
public static void CheckandCreateLogDirectory(string directoryPath)
{
if (!System.IO.Directory.Exists(directoryPath))
{
System.IO.Directory.CreateDirectory(directoryPath);
}
Directory = directoryPath;
}
public static void WriteLine(string writeLine, Status status)
{
if (Directory == null)
{
CheckandCreateLogDirectory(".\\Log\\");
}
using (System.IO.StreamWriter objWriter = new System.IO.StreamWriter(Directory + "Log" + DateTime.Now.ToString("ddMMyyyy") + ".log", true))
{
objWriter.WriteLine(string.Format("[{0}] {1}\t{2}", DateTime.Now, status.ToString(), writeLine));
}
}