为什么我的自定义事件会抛出异常?

Cap*_*ard 0 c# events

我正在编写一个记录用户空闲时间的程序,但是当我尝试运行该程序时,它会抛出一个Stack Overflow异常.

这些是我的自定义事件

public void OnInactive(EventArgs e)
{
    this.OnInactive(new EventArgs());
    do
    {
        var idle2 = GetIdleTime();
        GetIdleTime();
        System.Diagnostics.Debug.WriteLine(idle2);
    }
    while (timer.Interval > 5000);
}

public void OnActive(EventArgs e)
{
    this.OnActive(new EventArgs());
    if (timer.Interval < 5000)
    {
        var idle3 = GetIdleTime();
        System.Diagnostics.Debug.WriteLine(idle3);
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经打破了代码,试图找到问题的根源,这似乎在于this.OnInactive(new EventArgs());,但是我很难解决如何解决这个问题,因为我是自定义事件的初学者并且没有编码C#很久了.

对此问题的任何和所有帮助将不胜感激!

在先感谢=]

Lee*_*Lee 5

您的处理程序方法在输入时立即调用自身:

this.OnInactive(new EventArgs());
Run Code Online (Sandbox Code Playgroud)

这会导致一系列调用:

OnInactive - > OnInactive - > OnInactive - > ... - >

这将继续,直到你用完堆栈空间,StackOverflowException并由运行时抛出.

目前还不清楚你想通过递归调用实现什么,但你应该能够删除它.

您的OnActive处理程序中存在相同的问题.

编辑:在回应评论时,您似乎正试图在方法开始时提升事件本身.假设您的事件声明如下:

public event EventHandler InActive;
Run Code Online (Sandbox Code Playgroud)

然后你可以提高它:

EventHandler inactiveEvent = this.InActive;
if(inactiveEvent != null)
{
    inactiveEvent(this, e);
}
Run Code Online (Sandbox Code Playgroud)

同样适用于您的Active活动.