So, I have been trying to study for Exam 70-483 in C#, because I need to get my certifications fairly desperately.
However, Parallelism has just caused me a huge headache. I understand the basic idea, but a lot of code I've been reading implies the assumption that only async methods should used in async methods.
More or less, I'm asking what is the difference between My "WriteXMLAsync" and "WriteXMLAsyncTwo."
If I'm not mistaken, both are run in parallel to the main thread. So, whats the point of having all the awaits on the "WriteXMLAsync." It doesn't seem to be justified in anyway as it'll do the same thing as the second method if I'm right.
namespace TaskProgram
{
class Program
{
static void Main(string[] args)
{
Task TaskOne = Task.Factory.StartNew(() => WriteXMLAsync());
Task TaskTwo = Task.Factory.StartNew(() => WriteXMLAsyncTwo());
List<Task> TaskList = new List<Task> { TaskOne, TaskTwo };
Task.WaitAll(TaskList.ToArray());
Console.WriteLine("Both Tasks Have Finished.");
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
static async void WriteXMLAsync()
{
try
{
XmlWriterSettings XMS = new XmlWriterSettings();
XMS.Async = true;
using (XmlWriter Writer = XmlWriter.Create("FileAsyncOne.xml", XMS))
{
await Writer.WriteStartElementAsync("", "root", "");
await Writer.WriteEndElementAsync();
await Writer.FlushAsync();
}
}
catch (Exception Ex)
{
//Not what we'd normally do, but hey its good enough for this example.
Console.WriteLine("Encountered an Exception.");
}
}
static void WriteXMLAsyncTwo()
{
try
{
using (XmlWriter Writer = XmlWriter.Create("FileAsyncTwo.xml"))
{
Writer.WriteStartElement("root");
Writer.WriteEndElement();
}
}
catch(Exception Ex)
{
Console.WriteLine("Encountered an Exception.");
}
}
}
}
//Edit: Although, I have accepted Jodrell's answer. I would refer to his comment more for the information I was looking for.