简体   繁体   English

无法在后台任务中捕获异常

[英]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). 我的问题是,如果我调试Windows 8 Store App的后台任务并收到Error (异步方法调用时)。 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 ). 调试器跳到后台任务代码末尾的deferral.Complete()方法(在IBackgroundTaskRun方法中)。

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 . 您的InstantSchedule方法是async void并且在调用FetchLogsAsync之后将控制权返回给Run As a result, it jumps to catch statement, but after Run method finishes. 结果,它跳到catch语句,但是在Run方法完成之后。

You should make InstantSchedule method as Task and await on it: 您应该将InstantSchedule方法设置为Taskawait它:

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 . 注意, Run方法也应该是async

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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