昨天发现了一些东西,这让我意识到我很可能仍然缺少关于 C# 的基本花絮。
我有一个无状态服务结构应用程序。我在主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;
}
}
有人可以解释为什么会这样或指导我到哪里可以得到答案吗?我找不到任何解释这种行为的东西。
编辑:这不是“投掷”和“投掷前”之间的区别吗?因为,据我所知,没有解释我的问题,为什么该函数再次运行。该主题更多地是关于解释堆栈跟踪之间的区别throw
和各自的区别。throw new