I have a project that uses a Parallel.For call to perform the batch modification of files at once since they all take a considerable amount of time and I want to give feedback as the modification progresses. The entire process also backs up changed files and creates an undo batch command as it goes. The undo file MUST output the undo steps and flush the undo file buffer before moving onto to any other tasks so that all the batch steps (copy original file and delete the copy) get saved before the process of changing the file actually starts. For example... if I am changing two files "A.bin" "B.Bin" I want the batch file to say:
copy "A.original" "A.bin"
delete "A.original"
copy "B.original" "B.bin"
delete "B.original"
The problem is that asyncronous calls can switch between the parallel calls to the method that produces the above output which creates a file with the following output:
copy "A.original" "A.bin"
copy "B.original" "B.bin"
delete "A.original"
delete "B.original"
This creates a situation where if the program crashes or something goes wrong in the process between files during each step, the "undo" script ends up leaving off the "delete" lines making the undo batch leaving junk files which need to be deleted.
Is there a way to mark/force a method or block to be completed before windows switches to another thread? From what I understand about async/await, this has a different use case and will not accomplish what I need (which is the only search results that I can find when I look up how to do something like this online).
Here is the code that actually adds the steps to the batch file. This entire method must be executed in full without a thread switch:
internal static void AddCommit(CommitType type, string sourcePath, string destPath = null)
{
if ((type & CommitType.RestoreBackup) != 0)
{
if (destPath == null)
throw new ArgumentNullException();
UndoScript.WriteLine("copy \"" + sourcePath + "\" \"" + destPath + "\" /y");
}
if ((type & CommitType.UndoDeleteBackup) != 0)
UndoScript.WriteLine("delete \"" + sourcePath + "\" /q");
if ((type & CommitType.CommitDeleteBackup) != 0)
CommitScript.WriteLine("delete \"" + sourcePath + "\" /q");
UndoScript.Flush();
if (CommitScript != null)
CommitScript.Flush();
}