gpt4 book ai didi

c# - 在 C# 中抛出内部 Catch

转载 作者:行者123 更新时间:2023-11-30 14:46:03 25 4
gpt4 key购买 nike

昨天发现的一些东西让我意识到我很可能仍然缺少有关 C# 的基本花絮。

我有一个无状态 Service Fabric 应用程序。我在主 while 循环周围有一个 try-catch。如果我在这个循环中抛出一个异常,它就会跳出 while 循环并且服务有效地停止。如果我将 throw 添加到 catch 子句,服务将重新启动。

    protected override async Task RunAsync(CancellationToken cancellationToken)
{
try
{
long iterations = 0;
while (true)
{
cancellationToken.ThrowIfCancellationRequested();

await Task.Delay(TimeSpan.FromSeconds(3), cancellationToken).ConfigureAwait(false);

// Do stuff...

if (iterations > 4) {
throw new Exception();
}

ServiceEventSource.Current.ServiceMessage(this.Context, $"Working-{++iterations}");
}
}
catch (Exception ex)
{
// Log stuff...
throw;
}
}

谁能解释这是为什么,或者告诉我在哪里可以得到答案?我找不到任何可以解释此行为的内容。

编辑:它不是 Is there a difference between "throw" and "throw ex"? 的副本因为据我所知,它没有解释我的问题,为什么该功能再次运行。该主题更多地是关于解释堆栈跟踪的 throwthrow new 之间的区别。

最佳答案

根据您的描述,我们有两个选择:

  1. 您重新抛出异常,RunAsync Task 因该异常而失败
  2. 您没有重新抛出异常,RunAsync Task 正常完成(捕获的异常打破了 while 循环,因此方法退出)。

对于第一种情况,Service Fabric Stateless Service RunAsync doc进一步详细说明遇到异常时的行为,即从 FabricException 派生的异常将导致重新启动,而其他异常是有意或意外的服务中止并导致其停止。

正常完成在逻辑上意味着服务成功完成执行并将根据 Service Fabric Reliable Services Lifecycle doc 关闭。 .

关于c# - 在 C# 中抛出内部 Catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50755755/

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