ˈvɔlə
ˈvɔlə

Reputation: 10242

Can't catch exception in background task

My problem is, if I debug the background task of my Windows 8 Store App and get an Error (while async method call). It doesn't jump into my catch statment. The debugger jumps to the deferral.Complete() method at the end of the background task code (in the Run method of IBackgroundTask).

Here's my code:

public sealed class TileUpdater: IBackgroundTask {
    public void Run(IBackgroundTaskInstance taskInstance) {
        var defferal=taskInstance.GetDeferral();
        InstantSchedule();
        defferal.Complete(); // <- Debugger jumps over here after error
    }

    public static async void InstantSchedule() {
        try {
            [...]

            // Error occurs here
            IEnumerable<LogsEntity> logentities=
                account.IsAvailable
                    ?await TableStorage.FetchLogsAsync(account.Accountname, account.AccountKey, TileUpdater.RetrieveFilter())
                    :null;

            [...]
        }
        catch(Exception) {
            // Debugger doesn't break here 
        }
    }
}

Thanks

Upvotes: 1

Views: 1315

Answers (1)

Norfolc
Norfolc

Reputation: 458

Your InstantSchedule method is async void and returns control to the Run just after call to FetchLogsAsync. As a result, it jumps to catch statement, but after Run method finishes.

You should make InstantSchedule method as Task and await on it:

public async void Run(IBackgroundTaskInstance taskInstance) {
    var defferal=taskInstance.GetDeferral();
    await InstantSchedule();
    defferal.Complete();
}

public static async Task InstantSchedule() {
        [...]
}

Note, that Run method is also should be async.

Upvotes: 1

Related Questions