I am currently trying to read and write data to a xml file in c# using thread, I have a utilty class that has the function to read the XML file and then write the data into the xml. The way im doing it is as follows.
public class XMLUtil
{
String lockingObject = "";
public bool WriteToXml(Product product)
{
lock(lockingObject)
{
XDocument xDoc = XDocument.Load("file.xml")
}
//Code to add data to XElement
xDoc.Add(xElement)
lock(lockingObject)
{
XDocument xDoc = XDocument.Save("file.xml")
}
}
}
public class SomeOtherClass
{
XMLUtil xmlUtil = new XMLUtil();
private async void btn_Click(object sender, EventArgs e)
{
bool t = await Task.Run(() => xmlUtil.WriteToXml());
}
}
static class Program
{
// default methods
while (true)
{
t = await Task.Run(() => XMLUtil.CheckChanges());
await Task.Delay(20000);
}
}
I also have a background thread that keeps checking for the changes in the XML file to reload the view to the user, because of that I still get the IO/Exception saying that the file is already been used so it cannot be open... How can I fix it?