简体   繁体   中英

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:

// 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.

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). 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.

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 . This is called from Class A . Turns out Class A is destroyed occasionally and as TimeSetEvent is pinvoked (unmanaged) it carries on working. 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 .

The solution is to implement a method in Class B that kills the timer before removing Class A . Then, it will be safe to delete Class A and Class B won't make the application crash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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