Timer on a UWP

Hello,
I am currently programming a Universal Windows App with visual c#. I did some minor changes in the UWP starter app to read an i2c Signal. I was suggested to use the built in timer to read the data continuously but I have some difficulties implementing the timer. I tried to follow the code of the C++ API but the timer won't work.
Here is my code

mbl_mw_timer_create_indefinite(cppBoard, 100, 0, timerHandlerDelegate);

timerHandlerDelegate = new Fn_IntPtr(mwtimer =>
                {
                    var timerevent = mbl_mw_event_get_owner(mwtimer);
                    mbl_mw_event_record_commands(mwtimer);
                    mbl_mw_datasignal_read_with_parameters(i2c_signal, i2c_pnt);
                    mbl_mw_event_end_record(mwtimer, endrecord);
                });
mbl_mw_timer_start(mwtimer);
When starting the timer I always get the same error: System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
I'm not sure what the problem is. It would be great if someone could help me!

Comments

  • Move the mbl_mw_timer_start into the Fn_IntPtr delegate
  • Now it works! Thanks a lot! This is probably a silly question, but if the function timer start is in the timerDelegate, how do I stop the timer? 
  • I'm also having trouble when restarting the app. I get the same error as before (probably because the timer was already implemented once?)
  • Save the timer pointer returned to the delegate and use it later.  

    I assume you've never removed the previously created timers so eventually there are no more resources left to allocate.  You'll need to add a null pointer check to the delegate to handle this case and if it does fire, call mbl_mw_metawearboard_tear_down and try creating the timer again.  
This discussion has been closed.