RichPro RichPro - 1 year ago 131
C# Question

Error when using XDocument in code behind

I have a UWP project that requires data from an XML file. I am developing the project in Blend.

When I add the line:

XDocument xdoc = XDocument.Load("E:/VisualStudioRepo/ImportFromXML/ImportFromXML/Assets/XML/Book2.xml");

I get an error:

An exception of type 'System.InvalidOperationException' occurred in System.IO.FileSystem.dll but was not handled in user code

Additional information: Synchronous operations should not be performed on the UI thread. Consider wrapping this method in Task.Run.

I can replicate this error by just by starting a new project, adding a xaml button and the following code behind:

public void GetSentence()
XDocument xdoc = XDocument.Load("E:/VisualStudioRepo/ImportFromXML/ImportFromXML/Assets/XML/Book2.xml");

private void button_Click(object sender, RoutedEventArgs e)

I have tested my full Linq code in a Visual Studio Console application and I can read the xml perfectly there and output lists of all or part of the xml file. So the xml file is OK and my basic methodology seems to work. It just won't work in the UWP environment.

Do I really have to "wrap this method in a Task.Run"? If so, please tell me how to do it. What surprises me is that I can't see anyone else with this precise problem on the web despite hours of searching, so I suspect I am doing something wrong.

I am a self-confessed amateur programmer who loves programming (and an 'old bloke' as well), so please help me with a clear explanation and please don't tell me to go back to school as that was a real long time ago!

Answer Source

While I'm not too sure why you are getting this error, I will definitely help you out on using Task.Run().

Task.Run allows you to run tasks on a background thread, so that you don't block the UI thread.

You can use it like so:

private void button_Click(object sender, RoutedEventArgs e)
    var newTask = Task.Run(() => (GetSentence());

What this does is calls the GetSentence() method on a different thread, while still giving you the same result.

You can also do this as well to get the same effect!

var newTask = Task.Run(() => {  XDocument xdoc = XDocument.Load("E:/VisualStudioRepo/ImportFromXML/ImportFromXML/Assets/XML/Book2.xml"); });

Lastly, the Developer Network has a great article here with similar examples: You can find more info here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download