简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM