I have a method where I used Parallel.ForEach
to speed up processing, First it is picking small files and processing fast; for the big files, it is very slow and is slower than the for
loop. How can I improve the speed or should I try a different approach?
Please suggest or guide me how can I improve the speed.
public bool CheckQueueExist()
{
try
{
if (QueueVariables.NewFolderPath == "")
{
LoadFilePath();
}
string path = QueueVariables.NewFolderPath;
DirectoryInfo info = new DirectoryInfo(path);
var files = info.GetFiles().OrderBy(p => p.CreationTime)
.ThenBy(a => a.Name).Take(10000).ToArray();
var batchOfFiles = files
.Select((x, i) => new { Index = i, FullName = x.FullName, Name = x.Name })
.GroupBy(x => x.Index / 10)
.Select(x => x.Select(v => new { v.Name, v.FullName }).ToList())
.ToList();
bool commitstatus = false;
Parallel.ForEach(Partitioner.Create(
batchOfFiles, EnumerablePartitionerOptions.NoBuffering),
new ParallelOptions() { MaxDegreeOfParallelism = 2 }, batch =>
{
StringBuilder strQueryBuild = new StringBuilder();
List<string> filenamesToMove = new List<string>();
foreach (var file in batch)
{
string fullfilepath = file.FullName;
string Filename = file.Name;
try
{
string content = System.IO.File.ReadAllText(fullfilepath);
strQueryBuild.Append(content);
filenamesToMove.Add(fullfilepath);
}
catch (Exception ex)
{
commitstatus = false;
AppHelper.ErrrorLog(ex, "File in USE: " + fullfilepath);
}
}
int RowsAffected = 0;
try
{
string connstr = System.Configuration.ConfigurationManager
.ConnectionStrings["XYZ"].ConnectionString;
using (var conn = new NpgsqlConnection(connstr))
{
conn.Open();
var tra = conn.BeginTransaction();
try
{
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 0;
cmd.CommandText = strQueryBuild.ToString();
RowsAffected = cmd.ExecuteNonQuery();
if (RowsAffected == 0)
{
RowsAffected = 1;
}
tra.Commit();
commitstatus = true;
}
catch (Exception ex)
{
AppHelper.ErrrorLog(ex, "UploadFileData-Error1");
RowsAffected = -1;
tra.Rollback();
commitstatus = false;
}
}
}
catch (Exception ex)
{
commitstatus = false;
AppHelper.ErrrorLog(ex, "ProcessQueue-Error2");
}
if (commitstatus)
{
Parallel.ForEach(filenamesToMove, filepath =>
{
string Filename = Path.GetFileName(filepath);
MovetoSuccessFolder(filepath, Filename);
});
}
else
{
Parallel.ForEach(filenamesToMove, filepath =>
{
string Filename = Path.GetFileName(filepath);
MovetoFailureFolder(filepath, Filename);
});
}
});
return commitstatus;
}
catch (Exception ex)
{
AppHelper.ErrrorLog(ex, "CheckQueueExist");
return false;
}
finally
{
}
}