c# - Windows Phone 8 Accelerometer events -


i'm making first game windows phone (xna). use accelerometer change position of crosshair on screen:

position of crosshair

here code in initialize() function (note accelerometer local variable declared in function):

accelerometer accelerometer = new accelerometer(); accelerometer.currentvaluechanged += accelerometer_currentvaluechanged; accelerometer.start(); 

and event handler:

void accelerometer_currentvaluechanged(object sender, sensorreadingeventargs<accelerometerreading> e)         {             lock (accelerometervectorlock)             {                 accelerometervector = new vector3(                     (float)e.sensorreading.acceleration.x,                     (float)e.sensorreading.acceleration.y,                     (float)e.sensorreading.acceleration.z);             }         } 

this works fine on windows phone emulator, , on nokia lumia 520 connected computer , launching visual studio, when launch game in phone (not connected computer), accelerometer_currentvaluechanged event appears called once, on application startup.

my solution make accelerometer member of game class, code in initialize() this:

accelerometer = new accelerometer(); accelerometer.currentvaluechanged += accelerometer_currentvaluechanged; accelerometer.start(); 

so question is, why solution work? , why there difference between application launched vs , normally, on same device?

why solution works?

this solution works because you're keeping reference accelerometer. windows phone applications, .net applications, use automated system memory management. background process, called garbage collector, inspects objects in regular basis, detects not referenced anymore, , clean them. if declare accelerometer local variable, won't referenced anymore when function exits, , therefore cleaned. when declare member of class, alive long class lives.

why difference between application launched vs , normally, on same device?

when launching code visual studio, debugger attached. debugging, has impacts on way code executes. notably, makes garbage collector way less aggressive. explains why didn't have issue when testing debugger attached. note can achieve same result pressing control + f5 in visual studio: it'll start application without attaching debugger.


Comments