我有一个使用.NET Generic Host的
我查看了文档,但没有找到任何有关全局异常处理程序或类似机制的信息,可以捕获未处理的异常并防止应用程序崩溃。
是否有解决方法,以保护Generic Host和
编辑
我知道,在这里最简单的方法是尝试/捕获异常,并防止其冒泡。但我想知道是否有类似WinForms / WPF的机制,可以更全局地捕获此类异常并防止崩溃。
编辑
以下是代码的简化版本:
在这个例子中,很容易在
IHostedService
,用于接收来自OPC-UA接口的事件并处理它们。但是问题在于,如果在处理事件过程中出现未处理的异常,整个应用程序将崩溃。我查看了文档,但没有找到任何有关全局异常处理程序或类似机制的信息,可以捕获未处理的异常并防止应用程序崩溃。
是否有解决方法,以保护Generic Host和
IHostedService
免受未处理异常的影响?编辑
我知道,在这里最简单的方法是尝试/捕获异常,并防止其冒泡。但我想知道是否有类似WinForms / WPF的机制,可以更全局地捕获此类异常并防止崩溃。
编辑
以下是代码的简化版本:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
return new HostBuilder()
.UseEnvironment(environmentName)
.ConfigureLogging((hostContext, logging) =>
{
...
})
.ConfigureAppConfiguration((hostContext, builder) =>
{
builder
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true, true)
.AddEnvironmentVariables();
})
.ConfigureServices((hostContext, services) =>
{
services.AddSingleton<IHostedService, OpcClientHostedService>();
...
});
}
}
public class OpcClientHostedService : IHostedService
{
private readonly OpcConfiguration _opcConfiguration;
private readonly ILogger _logger;
private readonly OpcClient _opcClient;
public OpcClientHostedService(OpcConfiguration opcConfiguration, ILogger<OpcClientHostedService> logger)
{
_opcConfiguration = opcConfiguration;
_logger = logger;
_opcClient = new OpcClient(opcConfiguration.ServerUri);
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Connecting to OPC server with URI '{0}'", _opcConfiguration.ServerUri);
try
{
_opcClient.Connect();
}
catch (Exception ex)
{
_logger.LogCritical(ex, "Cannot connect to OPC server");
throw;
}
_logger.LogInformation("Connection to OPC server is successful");
CreateOpcObservable().Subscribe(async args => await ProcessOpcEvent(args));
return Task.CompletedTask;
}
private async Task ProcessOpcEvent(OpcValueChangedEventArgs args)
{
await MethodThatCanThrowAnException(args); // If the exception is not handled, the whole application crashes!
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Disconnecting to OPC server");
_opcClient.Disconnect();
_logger.LogInformation("Disconnection to OPC server is successful");
return Task.CompletedTask;
}
...
}
在这个例子中,很容易在
ProcessOpcEvent
方法中添加try/catch块,但是最好有一种机制来避免完全的应用程序崩溃。