简体   繁体   English

几秒钟后,TimeSetEvent失败(NullReferenceException)

[英]TimeSetEvent failing after a few seconds (NullReferenceException)

I'm using TimeSetEvent and its callback function is working but after a few seconds it fails EVEN if the callback function does no work at all: 我正在使用TimeSetEvent并且其回调函数正常工作,但是几秒钟后,即使回调函数根本无效,它也会失败:

// Vars
private TimerEventHandler timerRef;
private uint timerId = 0;

//Later, where I use TimeSetEvent
timerRef = new TimerEventHandler(CallbackFunction);
timerId = timeSetEvent(200, 10, timerRef, UIntPtr.Zero, TIME_KILL_SYNCHRONOUS | TIME_PERIODIC);

Even with 200ms delay it's not working properly. 即使延迟200毫秒,它也无法正常工作。

private void CallbackFunction(uint id, uint msg, UIntPtr userCtx, UIntPtr uIntPtr, UIntPtr intPtr)
{

// Even if this is empty, it will fail
}

I either get NullReferenceException(most of the times) or AccessViolationException (occasionally). 我要么得到NullReferenceException(大多数时候),要么得到AccessViolationException(偶尔)。 I suspect both coming from the same problem. 我怀疑两者都来自同一个问题。

Funny thing, I have exactly the same structure in another class and it works. 有趣的是,我在另一个类中具有完全相同的结构,并且可以正常工作。 I copied that class and here... It doesn't. 我复制了该课程,然后在这里……没有。 I get this error. 我得到这个错误。

I don't understand why it's not working (and in the other class it does) and how to solve it. 我不明白为什么它不起作用(在其他班级却不起作用)以及如何解决它。

PD: timerId returns an integer different than 0. I don't understand where this null comes frmo, if I comment TimerId = TimeSetEvent ... Code won't fail. PD:timerId返回一个不同于0的整数。如果我注释TimerId = TimeSetEvent ...,则我不知道该null出现在frmo的TimerId = TimeSetEvent 。代码不会失败。

After couple of days with my workmate reviewing more and more code we found the problem. 经过几天与我的同事一起审查越来越多的代码,我们发现了问题。 Have to say the question didn't have enough information to solve it, but we couldn't know. 不得不说这个问题没有足够的信息来解决,但是我们不知道。 It's very complex program and we couldn't imagine we needed code from other classes. 这是一个非常复杂的程序,我们无法想象我们需要其他类的代码。

The code above is in Class B . 上面的代码在Class B This is called from Class A . 这是从Class A调用Class A Turns out Class A is destroyed occasionally and as TimeSetEvent is pinvoked (unmanaged) it carries on working. 事实证明, Class A偶尔会被破坏,并且当TimeSetEvent 故障(不受管理)时,它会继续工作。 Therefore, when it tries to look for the callback function it has been disposed along with all contents from Class B and it gives a null reference exception . 因此,当它尝试查找回调函数时,它与Class B所有内容一起被放置了,并给出了null引用异常

The solution is to implement a method in Class B that kills the timer before removing Class A . 解决方案是在Class B实现一个方法 ,该方法在删除Class A之前终止计时器。 Then, it will be safe to delete Class A and Class B won't make the application crash. 然后,可以安全地删除Class A Class B不会使应用程序崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM