我的Windows Phone Silverlight 8.1应用程序有一个后台任务。
后台任务运行正常,但是当我在其中调用异步方法时,它只是在此阶段冻结。使用调试器,它就会停止。我不能单步执行代码或任何东西。
以下是我的代码:
public sealed class bgTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
DateTime timeNow = DateTime.Now;
TimeSpan minus28 = new TimeSpan(0, 28, 0);
DateTime timeGone = timeNow.Subtract(minus28);
int resultsCount = await GetCount();
ToastTemplateType toastTemplate = ToastTemplateType.ToastText02;
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
XmlNodeList textElements = toastXml.GetElementsByTagName("text");
textElements[0].AppendChild(toastXml.CreateTextNode("New Pictures!"));
textElements[1].AppendChild(toastXml.CreateTextNode(resultsCount + " new images in your area"));
ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));
_deferral.Complete();
}
private async Task<int> GetCount()
{
string page = "http://en.wikipedia.org/";
// ... Use HttpClient.
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
// ... Read the string.
string result = await content.ReadAsStringAsync();
// ... Display the result.
if (result != null &&
result.Length >= 50)
{
//resultsCount = 1888;
}
}
return 9999;
}
在调试时,它将进入GetCount()方法,然后停止在await GetCount()部分。
一直试图解决这个问题。非常感谢帮助。 :)
答案 0 :(得分:0)
您需要在类范围内定义延迟。这就是在创建和启动后台任务时要求推迟的。
public sealed class bgTask : IBackgroundTask
{
BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
public async void Run(IBackgroundTaskInstance taskInstance)
{
//Handle async stuff
_deferral.Complete();
}
}
有关此内容的更多信息,请访问:https://msdn.microsoft.com/en-us/windows/uwp/launch-resume/create-and-register-a-background-task