Is this thread safe?
I have a program that executes an SQL command on a number of files (selected by the user).
Here is where I create the threads:
var allThreads = new List<Task<bool>>();
if (fileList != null)
{
foreach (var file in fileList)
{
var fileName = Path.GetFileName(file);
if (File.Exists(file))
{
Log.AddToLog("Beginning to Process File: " + fileName);
if (!ValidateFile(file))
{
Log.AddToLog(String.Format("Error! {0} is not a valid file for the {1}. Skipping this file.", fileName, JsonSettingsList.NameId));
IsErrorsInLog = true;
}
else
{
var fileToProcess = file; //need to make copy for threading loop, otherwise it acts screwy
var newTask = Task.Factory.StartNew<bool>(() => ProcessFile(fileToProcess));
allThreads.Add(newTask);
}
}
else
{
Log.AddToLog(String.Format(CultureInfo.CurrentCulture, "File {0} Does not Exist. File not processed.", fileName));
IsErrorsInLog = true;
}
}
//check result, if any of them return true, then there are errors in the log, and the user needs to be alerted.
foreach (var task in allThreads)
{
try
{
var didThreadFail = task.Result;
if (!IsErrorsInLog)
{
IsErrorsInLog = didThreadFail;
}
}
catch (AggregateException aggEx)
{
foreach (Exception ex in aggEx.InnerExceptions)
{
Log.AddToLog(string.Format("Caught exception '{0}'",
ex.Message));
IsErrorsInLog = true;
}
}
finally
{
task.Dispose();
}
}
}
and then here is the code where I am actually accessing the database, inside of the ProcessFile()
function:
//initialize oracle connection
oraConnection.Open();
using (var command = new OracleCommand(sqlText, oraConnection))
{
command.Transaction = command.Connection.BeginTransaction();
foreach (var line in fileByLine.Where((i, index) => index > 0))
{
if (!String.IsNullOrWhiteSpace(line))
{
//add parameters
command.ExecuteNonQuery();
}
}
command.Transaction.Commit();
Log.AddToLog("Successfully Processed " + filePath);
}
oraConnection.Close();
The comments are where I have omitted unnecessary code for the sake of simplicity.