我有以下代码可以从通用应用程序调用,并且可以正常运行
// 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分钟后运行,它将在这一行进行故障转移?
最佳答案
问题解决了。
我将async关键字添加到backgroundTask Run方法中,以便可以调用async方法。
取而代之的是,我从后台Run方法中删除了异步键盘输入,并使用
var result = Task.Run(async() => {
return myAsyncMethod();
}).Result;
现在一切正常
关于c# - 在Windows通用应用中,由backgroundTask使用httpRequest.GetResponseAsync()失败吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31852926/