我有一个需要来自 XML 文件的数据的 UWP 项目。我正在 Blend 中开发项目。
当我添加行时:
XDocument xdoc = XDocument.Load("E:/VisualStudioRepo/ImportFromXML/ImportFromXML/Assets/XML/Book2.xml");
我得到一个错误:
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.
我可以通过启动一个新项目,添加一个 xaml 按钮和下面的代码来复制这个错误:
public void GetSentence()
{
XDocument xdoc = XDocument.Load("E:/VisualStudioRepo/ImportFromXML/ImportFromXML/Assets/XML/Book2.xml");
}
private void button_Click(object sender, RoutedEventArgs e)
{
GetSentence();
}
我已经在 Visual Studio 控制台应用程序中测试了我的完整 Linq 代码,我可以在那里完美地读取 xml 并输出全部或部分 xml 文件的列表。所以 xml 文件没问题,我的基本方法似乎有效。它只是不能在 UWP 环境中工作。
我真的必须“将此方法包装在 Task.Run 中”吗?如果是这样,请告诉我该怎么做。令我惊讶的是,尽管进行了数小时的搜索,但我在网络上看不到任何其他人遇到这个确切的问题,所以我怀疑我做错了什么。
我自认是一个热爱编程的业余程序员(也是一个“老家伙”),所以请帮我解释清楚,请不要让我回学校,因为那是真实的很久以前!
最佳答案
虽然我不太确定您为什么会收到此错误,但我一定会帮助您解决使用 Task.Run()
的问题。
Task.Run allows you to run tasks on a background thread, so that you don't block the UI thread.
你可以这样使用它:
private void button_Click(object sender, RoutedEventArgs e)
{
var newTask = Task.Run(() => (GetSentence());
}
这样做是在不同的线程上调用 GetSentence() 方法,同时仍然为您提供相同的结果。
您也可以这样做以获得相同的效果!
var newTask = Task.Run(() => { XDocument xdoc = XDocument.Load("E:/VisualStudioRepo/ImportFromXML/ImportFromXML/Assets/XML/Book2.xml"); });
最后,开发者网络在这里有一篇很棒的文章,里面有类似的例子:You can find more info here
关于c# - 在代码隐藏中使用 XDocument 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40814580/