我有以下代码,我可以从我的通用应用程序调用,它工作正常
// 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手动运行任务,它会在这一行上进行故障转移,如果我让backgroundTask在15分钟后自行运行,它会在此行上进行故障转移?
答案 0 :(得分:0)
问题解决了。
我在我的backgroundTask Run方法中添加了async关键字,因此我可以调用我的异步方法。
而不是这个,我从我的后台Run方法中删除了异步keywork,并使用
调用了异步代码var result = Task.Run(async() => {
return myAsyncMethod();
}).Result;
现在全部工作