I want to use a Portable Class Library in a Windows Phone 8 app. The PCL contains async methods only and that's fine. But I want to call one of the methods from the Application_Launching
event handler and wait for the result, so that I can instantly use it, as soon as the main page gets loaded.
These similar questions didn't help me:
- HttpWebRequest synchronous on Windows Phone 8
- call async methods in synchronized method in windows phone 8
For easy reproduction the following code is similar but more simple:
The PCL:
public class TestAsyncClass
{
public async Task<string> SendRequestAsync()
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync("http://www.google.com").ConfigureAwait(false);
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}
}
As you can see, there's ConfigureAwait(false)
for the method calls that are being awaited, so there shouldn't be a deadlock because of some captured context that the method wants to return to. At least that's how I understood Stephen Cleary's blog article on that topic: http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
The App.xaml.cs:
private async void Application_Launching(object sender, LaunchingEventArgs e)
{
TestAsyncLib.TestAsyncClass tac = new TestAsyncLib.TestAsyncClass();
//string result = await tac.SendRequestAsync(); // GlobalData.MyInitString is still empty in MainPage.xaml.cs OnNavigatedTo event handler
string result = tac.SendRequestAsync().Result; // Gets stuck
GlobalData.MyInitString = result;
}
As written in the comments, when calling the method asynchronously, GlobalData.MyInitString is still empty when trying to access it in the MainPage.xaml.cs OnNavigatedTo event handler, because the UI thread gets the focus immediately and launches the main page before the library method is able to return any results. And calling the method synchronously causes the library method to get stuck.
Here's the MainPage.xaml.cs:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
System.Diagnostics.Debug.WriteLine(GlobalData.MyInitString);
}
For completeness, GlobalData.cs:
public static class GlobalData
{
public static string MyInitString { get; set; }
}
I'm thankful for any help!