Search code examples
c#.netwin-universal-appbackground-task

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


I have the following code that i can call from my universal app, and it works fine

// 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()) {
    ....
}

But this code seems to stop on var httpResponse = await httpRequest.GetResponseAsync() when i execute this from a backgroundTask?

To setup my background task, i have the following code.

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);
    });
}

Why is this not working? If i ran the task manually using visual studio it fails over on this line and it fails over on this line if i let the backgroundTask run itself after 15 minutes?


Solution

  • Problem solved.

    I added the async keyword to my backgroundTask Run method so i could call my async method.

    Instead of this, i removed the async keywork from my background Run method, and called the async code using

    var result = Task.Run(async() => {
        return myAsyncMethod();
    }).Result;
    

    Now all working