I have a function which reads each file from a directory and upload it to a database.
I cannot work out how to wait for the task to finish before it goes back to the foreach loop, as it seems to do it straight away, where as the task takes a few seconds:
foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml"))
{
//load file
currentReader = new XmlDataReader(transferInstructions, file);
currentReader.RowsUploaded += new EventHandler<RowsUploadedEventArgs>(currentReader_RowsUploaded);
currentReader.TableUploaded += new EventHandler<TableUploadedEventArgs>(currentReader_TableUploaded);
currentTask = new Task(() => currentReader.executeBulkCopy(initialConnString, workingDatabase));
currentTask.ContinueWith(task =>
{
cleanUp(task);
//MessageBox.Show("Complete!");
});
currentTask.Start();
writeResult("Started the transfer process.");
cmdDataTransfer.Text = "CANCEL TRANSFER";
cmdDataTransfer.ForeColor = Color.DarkRed;
transferAction = () => cancelCurrentReader();
}
I need to wait for where the MessageBox.show would be before it continues the foreach loop.
It takes a few seconds to get to the
cleanUp(task);
//MessageBox.Show(“Complete!”);
section.
Thanks.
The async-awqait pattern in C# 5 / .NET 4.5 is a perfect match for this. I see you’ve tagged this as .NET4, but if you can use the Async Targeting Pack, there is a very elegant way of doing this:
If you have to keep it VS2010, you’ll have to emulate what async-await does, something along the lines of:
EDIT Now that I think about it there’s also a much simpler way. You can have the entire loop running in a task of its own (delegating to the synchronization context for GUI work). Using the conventions of the code above: