下面的代码有一个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);
}
}
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)
已被删除,因为任务正在被替换,这显然是行不通的。