gpt4 book ai didi

c# - 如何确保操作不会使整个应用程序崩溃?

转载 作者:太空狗 更新时间:2023-10-30 00:29:30 28 4
gpt4 key购买 nike

我有一个应用程序执行一些额外的工作,例如清理旧日志、发送通知等。如果一项工作失败,我不希望整个应用程序停止工作并且不执行剩下的工作。

例如,

await SendUsersBirthdayEmailsAsync(); // <-- if something fails while trying to send birthday emails here, I don't want the app to stop working and not clean logs and so on...
await DeleteOutdatedLogsAsync();
await SendSystemNotificationsAsync();

你会推荐我去做什么?

最佳答案

对可能失败的代码的每个部分使用 try-catch block 。
根据您的需要,使用 try-catch-finally block 。

在每个 catch block 上,根据需要记录异常。我使用 Nlog 进行日志记录,所以我建议调查一下。

try{
//do work here
}
catch(Exception e){
//log exception here
}
//optional
finally{
//do optional needed work here
}

像这样:

public bool SendUsersBirthdayEmailsAsync(){
try{
SendMail();
}
catch(Exception e){
LogException(e);
}
//optional
finally{
OptionalWork();
}
}

编辑:关于避免使用通用异常

您始终可以使用多个 catch block 来为每种类型的异常定义不同的行为。当您知道会发生哪种异常时,这很有用。
示例:

public bool SendUsersBirthdayEmailsAsync(){
try{
SendMail();
}
catch (ThreadAbortException tae)
{
LogException(tae);
//do something specific
}
catch (ThreadInterruptedException tie)
{
LogException(tie);
//do something specific
}
catch(Exception e){
LogException(e);
}
//optional
finally{
OptionalWork();
}
}

编辑 2:Official Microsoft guidance用于异常处理。

Use try/catch blocks around code that can potentially generate an exception and your code can recover from that exception. In catch blocks, always order exceptions from the most derived to the least derived. All exceptions derive from Exception. More derived exceptions are not handled by a catch clause that is preceded by a catch clause for a base exception class. When your code cannot recover from an exception, don't catch that exception. Enable methods further up the call stack to recover if possible.

Clean up resources allocated with either using statements, or finally blocks. Prefer using statements to automatically clean up resources when exceptions are thrown. Use finally blocks to clean up resources that don't implement IDisposable. Code in a finally clause is almost always executed even when exceptions are thrown.

关于c# - 如何确保操作不会使整个应用程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57590877/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com