Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 961
Mahdi Avatar asked Nov 26 '12 17:11

Mahdi


1 Answers

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).

like image 194
Servy Avatar answered Oct 09 '22 22:10

Servy