首页 > 解决方案 > 如何从我无法直接访问的线程中捕获异常?

问题描述

我开发了一个能够运行一些插件的 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);
    }
}

标签: c#.net.net-core

解决方案


您还可以使用AppDomain.UnhandledException 事件

请注意,您无法从此类异常中恢复。


推荐阅读