httpRequest.GetResponseAsync() 在 windows 通用应用程序中被 backgroundTask 使用时失败?

httpRequest.GetResponseAsync() fails in windows universal app when used by backgroundTask?

我有以下代码可以从我的通用应用程序调用,它工作正常

// create our request with our data
var data = new JsonObject();
data.Add("param", JsonValue.CreateStringValue("abc"));

// convert to bytes
var dataAsBytes = System.Text.Encoding.UTF8.GetBytes(data.Stringify());

var httpRequest = HttpWebRequest.Create(URL + "Add");
httpRequest.Method = "POST";
httpRequest.ContentType = "application/json;charset=utf-8";

using (var requestStream = await httpRequest.GetRequestStreamAsync())
{
    requestStream.Write(dataAsBytes, 0, dataAsBytes.Length);    
}

var httpResponse = await httpRequest.GetResponseAsync();

using (var responseStream = httpResponse.GetResponseStream()) {
    ....
}

但是当我从 backgroundTask 执行此代码时,此代码似乎在 var httpResponse = await httpRequest.GetResponseAsync() 处停止?

要设置我的后台任务,我有以下代码。

var taskRegistered = false;
var taskName = "Upload Background Task";
var background = Windows.ApplicationModel.Background;
var iter = background.BackgroundTaskRegistration.allTasks.first();

while (iter.hasCurrent) {
    var task = iter.current.value;

    if (task.name === taskName) {
        taskRegistered = true;
        break;
    }

    iter.moveNext();
}

if (taskRegistered) {
    successCallback(); // my javascript success callback
} else {
    Windows.ApplicationModel.Background.BackgroundExecutionManager.requestAccessAsync().then(function () {
        var builder = new Windows.ApplicationModel.Background.BackgroundTaskBuilder();

        builder.name = taskName;
        builder.taskEntryPoint = "CordovaApp.Library.UploadTask";
        builder.setTrigger(new Windows.ApplicationModel.Background.TimeTrigger(15, false));
        builder.addCondition(new Windows.ApplicationModel.Background.SystemCondition(Windows.ApplicationModel.Background.SystemConditionType.internetAvailable));

        return builder.register();
    }).done(function () {
        successCallback();
    }, function (err) {
        errorCallback(err);
    });
}

为什么这不起作用?如果我 运行 使用 visual studio 手动执行任务,它会在此行上进行故障转移,如果我在 15 分钟后让 backgroundTask 运行 本身,它会在此行上进行故障转移?

问题已解决。

我将 async 关键字添加到我的 backgroundTask 运行 方法中,这样我就可以调用我的异步方法。

取而代之的是,我从后台 运行 方法中删除了异步键,并使用

调用了异步代码
var result = Task.Run(async() => {
    return myAsyncMethod();
}).Result;

现在一切正常