Mahdi
Mahdi

Reputation: 1827

Using async function in static methods

I have a static method that in it I call async method (xmlHelper.LoadDocument()). and I call this method in a property at Setter section

internal static IEnumerable<Word> LoadTenWords(int boxId)
{
     XmlHelper xmlHelper = new XmlHelper();
     XDocument xDoc = xmlHelper.LoadDocument().Result;
     return xDoc.Root.Descendants("Word").Single(...)
} 

As you know LoadTenWord is static and cannot be a async method, so I call LoadDocument with Result property. When I run my app the application don't work but when I debug it and I wait in following line

XDocument xDoc = xmlHelper.LoadDocument().Result;

everything is ok!!! I think, without await keyword, C# doesn't wait for the process completely finished.

do you have any suggestion for solving my problem?

Upvotes: 9

Views: 23237

Answers (1)

Servy
Servy

Reputation: 203822

The fact that the method is static does not mean it can't be marked as async.

internal static async Task<IEnumerable<Word>> LoadTenWords(int boxId)
{
    XmlHelper xmlHelper = new XmlHelper();
    XDocument xDoc = await xmlHelper.LoadDocument();
    return xDoc.Root.Descendants("Word").Select(element => new Word());
}

Using Result results in the method blocking until the task is completed. In your environment that's a problem; you need to not block but merely await the task (or use a continuation to process the results, but await is much easier).

Upvotes: 16

Related Questions