【发布时间】:2014-04-25 09:30:00
【问题描述】:
我想在 Windows Phone 8 应用程序中使用可移植类库。 PCL 仅包含异步方法,这很好。但我想从Application_Launching 事件处理程序中调用其中一种方法并wait 等待result,这样我就可以在主页面上立即使用它被加载。
这些类似的问题对我没有帮助:
- HttpWebRequest synchronous on Windows Phone 8
- call async methods in synchronized method in windows phone 8
为了便于复制,下面的代码类似但更简单:
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);
}
}
}
如您所见,正在等待的方法调用有ConfigureAwait(false),因此不应该因为方法想要返回的某些捕获的上下文而出现死锁。至少我是这样理解Stephen Cleary关于该主题的博客文章:http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
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;
}
如cmets中所写,异步调用该方法时,在MainPage.xaml.cs OnNavigatedTo事件处理程序中尝试访问时,GlobalData.MyInitString仍然为空,因为UI线程立即获得焦点并启动主页在库方法能够返回任何结果之前。并且同步调用方法会导致库方法卡住。
这是 MainPage.xaml.cs:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
System.Diagnostics.Debug.WriteLine(GlobalData.MyInitString);
}
为了完整起见,GlobalData.cs:
public static class GlobalData
{
public static string MyInitString { get; set; }
}
感谢您的帮助!
【问题讨论】:
-
与其进行阻塞等待,您可能应该重新考虑您的 UI 模型并将
await与indefinite progress indicator 一起使用,然后在SendRequestAsync完成时加载正常的 UI。
标签: c# windows-phone-8 asynchronous windows-phone async-await