async public void PlayRound(TimeSpan roundTimeSpan) { DateTime endTime = DateTime.Now + roundTimeSpan; score = 0; await App.Current.InvokeOnUIThread( () => { ScoreBlock.Text = "0"; }); while (DateTime.Now < endTime) { LightPin.Write(LedOffState); await App.Current.InvokeOnUIThread( () => { LedEllipse.Fill = grayBrush; }); if (SwitchPin.Read() != ButtonPressedState) { await waitForStart(); } await RandomWait(); await App.Current.InvokeOnUIThread( () => { ScoreBlock.Text = score.ToString(); }); } }
void performDelay(float delayInMilliseconds) { timerStarts = DateTime.Now; waitComplete = false; using (EventWaitHandle tmpEvent = new ManualResetEvent(false)) { tmpEvent.WaitOne(TimeSpan.FromMilliseconds(delayInMilliseconds)); } timerEnds = DateTime.Now; LightPin.Write(LedOffState); App.Current.InvokeOnUIThread( () => { Timeblock.Text = "Press the button to start"; LedEllipse.Fill = grayBrush; }); waitComplete = true; }
async Task RandomWait() { await App.Current.InvokeOnUIThread( () => { Timeblock.Text = "Waiting"; }); LightPin.Write(LedLitState); await App.Current.InvokeOnUIThread( () => { LedEllipse.Fill = LitBrush; }); string message = ""; DateTime buttonReleased; var tcs = new TaskCompletionSource <object>(); TypedEventHandler <GpioPin, GpioPinValueChangedEventArgs> waitingLambda = (s, e) => { if (s.Read() != ButtonPressedState) { if (!waitComplete) { message = "Fail"; score = score + 10000; } else { buttonReleased = DateTime.Now; TimeSpan reactionTime = buttonReleased - timerEnds; score = score + reactionTime.Milliseconds; message = "Score:" + score.ToString(); } tcs.TrySetResult(null); } }; try { SwitchPin.ValueChanged += waitingLambda; int delayTime = playerRand.Next(1000, 3000); launchDelay(delayTime); await tcs.Task; } finally { SwitchPin.ValueChanged -= waitingLambda; } await App.Current.InvokeOnUIThread( () => { Timeblock.Text = message; }); }