相关疑难解决方法(0)

HttpClient GetAsync在Windows 8上的后台任务中失败

我有一个Win RT应用程序,它有一个后台任务,负责调用API来检索自己更新所需的数据.但是,我遇到了一个问题; 在后台任务之外运行时,调用API的请求可以正常工作.在后台任务中,它失败了,并且还隐藏了任何可以帮助指出问题的异常.

我通过调试器跟踪此问题以跟踪问题点,并验证执行在GetAsync上停止.(我传递的URL有效,URL在不到一秒的时间内响应)

var client = new HttpClient("http://www.some-base-url.com/");

try
{
    response = await client.GetAsync("valid-url");

    // Never gets here
    Debug.WriteLine("Done!");
}
catch (Exception exception)
{
    // No exception is thrown, never gets here
    Debug.WriteLine("Das Exception! " + exception);
}
Run Code Online (Sandbox Code Playgroud)

我读过的所有文档都说允许后台任务拥有所需的网络流量(当然会受到限制).所以,我不明白为什么会失败,或者知道任何其他方法来诊断问题.我错过了什么?


UPDATE/ANSWER

感谢史蒂文,他指出了解决问题的方法.在确保定义的答案就在那里,利益在这里是后台任务前和修复程序后:

之前

public void Run(IBackgroundTaskInstance taskInstance)
{
    BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

    Update();

    deferral.Complete();
}

public async void Update()
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

public async void Run(IBackgroundTaskInstance taskInstance) // added 'async'
{
    BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

    await Update(); // added …
Run Code Online (Sandbox Code Playgroud)

c# background-process windows-8 windows-runtime

10
推荐指数
1
解决办法
3837
查看次数

UWP后台任务5次后没有运行

我正在关注https://docs.microsoft.com/en-us/windows/uwp/launch-resume/create-and-register-a-background-task文档以创建一个后台任务,该任务将每15分钟运行一次并ping一项服务.

  1. 使用实现IBackgroundTask的公共密封类创建了一个Windows运行时组件项目

    namespace PeriodicBackgroundTask
    {
        public sealed class FifteenMinutePeriodicTimer : IBackgroundTask
        {
            private static readonly FileLogWriter mWriteLogToFile = new FileLogWriter();
            public FifteenMinutePeriodicTimer() { }
    
            public void Run(IBackgroundTaskInstance taskInstance)
            {
                try
                {
                    taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
                    mDeferral = taskInstance.GetDeferral();
                    mWriteLogToFile.log("Starting periodic timer at " + DateTime.Now.ToString());
    
                    // Calling method to do a Post call to a service.
    
                    mWriteLogToFile.log("Finishing periodic timer at " + DateTime.Now.ToString());
                }
                catch (Exception ex)
                {
                    mWriteLogToFile.log("Fifteen Minute periodic timer failed.", ex);
                }
                finally
                {
                    // …
    Run Code Online (Sandbox Code Playgroud)

c# windows-10 uwp windows-10-universal

6
推荐指数
1
解决办法
1026
查看次数