Reputation: 11599
I have the following code in a library Helper.dll. This assembly has an embedded XML file called Products.XML. The method GetProducts
works fine. But it takes few seconds to respond because it is synchronous. I want to release the UI when this load operation was going on.
There are no async calls are available for LINQ to XML operations like XDocument.Load
, so I can not use async
and await
here.
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");
}
}
Upvotes: 0
Views: 551
Reputation: 116548
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:
var elements = await Task.Run(() => LookupUtil.GetProducts());
What you are basically doing is treating a block of synchronous code asynchronously.
Upvotes: 3