提问者:小点点

停止异步lambda传播向上调用堆栈的异常


下面的代码有一个TaskMonitor类,它是Stephen Cleary的NotifyTask类的修改版本。Worker类使用TaskMonitor类异步运行Worker.CheckStatus。

Worker.CheckStatus经常会引发异常(例如数据库连接问题)。我希望TaskMonitor.Monitor阻止异常到达Program.Main并通过Exception和InnerException属性公开它。TaskMonitor.Monitor中的catch块被命中,但没有像预期的那样吞下异常;异常会传递给program.main并使应用程序崩溃。如何停止TaskMonitor.Monitor中的异常?

public sealed class TaskMonitor {
    // Based on Stephen Cleary's NotifyTaskCompletion:
    // https://github.com/StephenCleary/Mvvm/blob/master/future/Nito.Mvvm.Async/NotifyTask.cs

    public TaskMonitor(Task task = null) {
        Task = task;
    }

    public AggregateException Exception {
        get {
            return Task?.Exception;
        }
    }

    public Exception InnerException {
        get {
            return Exception?.InnerException;
        }
    }

    public bool IsCompleted {
        get {
            return Task != null && Task.IsCompleted;
        }
    }

    public bool IsRunning {
        get {
            return Task != null && !Task.IsCompleted;
        }
    }

    private async Task Monitor(Task task) {
        try {
            if(task != null) {
                await task;
            }
        }
        catch {
            // Drop exceptions
        }
        finally {
            // do other stuff here like raise PropertyChanged
        }
    }

    private Task _task;

    public Task Task {
        get => _task;
        set {
            if(Task != value) {
                _task = value;
                _ = Monitor(Task);
            }
        }
    }
}

public class Worker {
    public Worker() {
        CheckStatusMonitor = new TaskMonitor();
    }

    public void CheckStatus() {
        if(!CheckStatusMonitor.IsRunning) {
            CheckStatusMonitor.Task = Task.Run(async () => {
                var newStatus = WorkerStatus.Unknown;
                try {
                    // Force a database connection failure
                    var cn = new SqlConnection();
                    await cn.OpenAsync();

                    newStatus = WorkerStatus.Good;
                }
                catch(Exception ex) {
                    newStatus = WorkerStatus.Error;
                    throw ex;
                }
                finally {
                    Status = newStatus;
                }
            });
        }
    }

    public TaskMonitor CheckStatusMonitor { get; private set; }

    public WorkerStatus Status { get; private set; }
}

public enum WorkerStatus {
    Unknown,
    Error,
    Good,
}

class Program {
    public static async Task Main() {
        var worker = new Worker();
        worker.CheckStatus();
        await worker.CheckStatusMonitor.Task;
        Debug.WriteLine(worker.CheckStatusMonitor.ErrorMessage);
    }
}

共1个答案

匿名用户

TaskMonitor.Monitor中的catch块被命中,但没有像预期的那样吞下异常;异常会传递给program.main并使应用程序崩溃。如何停止TaskMonitor.Monitor中的异常?

main中,您的代码正在执行Await Worker.CheckStatusMonitor.task;TaskMonitor.task返回的任务是从Worker.CheckStatus返回的task.Run任务,而不是从TaskMonitor.Monitor返回的任务。

如果要忽略异常,则需要await正确的任务:

public Task Task {
  get => _task;
  set {
    _task = Monitor(value);
  }
}

请注意,if(Task!=value)已被删除,因为任务正在被替换,这显然是行不通的。

相关问题