[英]Changing Sync call to Async
I have the following code in a library Helper.dll . 我在库Helper.dll中有以下代码。 This assembly has an embedded XML file called Products.XML . 该程序集具有一个称为Products.XML的嵌入式XML文件。 The method GetProducts
works fine. GetProducts
方法可以正常工作。 But it takes few seconds to respond because it is synchronous. 但由于它是同步的,因此需要花费几秒钟的时间进行响应。 I want to release the UI when this load operation was going on. 我想在进行此加载操作时释放UI。
There are no async calls are available for LINQ to XML operations like XDocument.Load
, so I can not use async
and await
here. 没有异步调用可用于LINQ到 XDocument.Load
类的XML操作,因此我不能await
这里使用async
和await
。
Appreciate any answer. 感谢任何答案。
public static class LookupUtil
{
public static IEnumerable<XElement> GetProducts()
{
var stream = Assembly.
GetExecutingAssembly().
GetManifestResourceStream("Helper.Products.XML");
var reader = new XmlTextReader(stream);
var document = XDocument.Load(reader);
return document.Descendants("Products");
}
}
If you don't have any asynchronous operations inside that method don't change it and keep it synchronous . 如果该方法内部没有任何异步操作,请不要更改它并使它保持同步 。
use Task.Run
when you call it from the UI thread to offload that synchronous work to a different thread and await
the returned task: 从UI线程调用Task.Run
时,可以将同步工作卸载到另一个线程,并await
返回的任务:
var elements = await Task.Run(() => LookupUtil.GetProducts());
What you are basically doing is treating a block of synchronous code asynchronously. 基本上,您正在做的是异步处理同步代码块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.