c# - 如何从我无法直接访问的线程中捕获异常?
问题描述
我开发了一个能够运行一些插件的 Windows 服务。由于其性质,在开发 Windows 服务时,Start 和 Stop 方法应尽可能快地运行和返回。该Start
方法运行Start
来自所有插件的方法,这些插件也不应该阻止执行。在这个例子中,两个插件都实例化了一个在后台运行的 Threading.Timer。
执行顺序如下。箭头表示在不同线程中运行的内容:
-> MyService.Start -> pA.Start -> pb.Start -> return
\_> DoWork() \
\_> DoWork()
由于两者DoWork()
都在计时器内运行,因此如果发生异常,我将无法捕捉到它。如果我可以修改 PluginA 和 PluginB,这很容易避免,但我不能。
关于我可以做些什么来避免这个问题的任何建议?提前致谢。
以下代码是对真实代码的过度简化:
public class MyService
{
private PluginA pA = new PluginA();
private PluginB pB = new PluginB();
// Windows Service runs Start when the service starts. It must return ASAP
public void Start()
{
// try..catch doesn't capture PluginB's exception
pA.Start();
pB.Start();
}
// Windows Service runs Stop when the service Stops. It must return ASAP
public void Stop()
{
pA.Stop();
pB.Stop();
}
}
// I have no control over how this is developed
public class PluginA
{
private Timer _timer;
public void Start()
{
_timer = new Timer(
(e) => DoWork(),
null,
TimeSpan.Zero,
TimeSpan.FromSeconds(10));
}
private void DoWork()
{
File.AppendAllText(
"C:/log.txt",
"hello" + Environment.NewLine);
}
public void Stop()
{
_timer.Change(Timeout.Infinite, 0);
}
}
// I have no control over how this is developed
public class PluginB
{
private Timer _timer;
public void Start()
{
_timer = new Timer(
(e) => DoWork(),
null,
TimeSpan.Zero,
TimeSpan.FromSeconds(10));
}
private void DoWork()
{
File.AppendAllText(
"C:/log.txt",
"Goodbye" + Environment.NewLine);
throw new Exception("Goodbye");
}
public void Stop()
{
_timer.Change(Timeout.Infinite, 0);
}
}
解决方案
您还可以使用AppDomain.UnhandledException 事件。
请注意,您无法从此类异常中恢复。
推荐阅读
- javascript - 加载页面时如何打开模块/画布?
- python - 如何使用 scikit-learn 在 python 中聚类后向气团轨迹?
- vba - VBA 中的幻灯片计数变量 - Powerpoint
- node.js - Bootstrap 列在 IE 11 中的行为不符合预期
- autodesk-forge - 是否有 Autodesk Forge API 可用于管理 Autodesk BIM 360 Docs 中的审批工作流?
- flutter - 在颤振中从 QuerySnapshot 中提取数据
- react-native - 反应原生的 iframe
- javascript - discord.js bot 嵌入消息图像未显示
- php - 颤振,我的 DataTable 和 php Json 输出问题......无法解决
- string - 如何在飞镖中从右到特定字符获取所有字符