I have a bug that is kicking my rear and I know its a simple task/threading issue that I’m not remembering how to handle. I know someone here will see the answer in seconds. This is a UWP app.
If I let it run as-is then when the timer ticks sometimes SetLampColorAsync() does something and my bulbs change color. However, if I put a debug break in SetLampColorAsync() and step through it then it works every time. And sometimes once I’ve stepped through it a few times then it will work on its own for a long while. There’s something thread/task related that I’m forgetting. I’ve tried every arrangement of Task & Dispatcher functions that I can think of and nothing helps. Any ideas are greatly appreciated.
public sealed partial class MainPage : Page
{
// AllJoyn stuff
private List<LampStateConsumer> _lampStateConsumers;
...
public MainPage()
{
this.InitializeComponent();
_lampStateConsumers = new List<LampStateConsumer>();
...
var timer = new DispatcherTimer();
timer.Tick += Timer_Tick;
timer.Interval = new TimeSpan(0, 0, 5);
timer.Start();
}
private async Task SetLampColorAsync(LampStateConsumer consumer)
{
var color = _cheerlights.Colors[_currentColor];
await consumer.SetHueAsync(color.Hue);
await consumer.SetSaturationAsync(color.Saturation);
}
private async void Timer_Tick(object sender, object e)
{
var newColor = await _cheerlights.GetCurrentColorAsync();
if (newColor == _currentColor) return;
_currentColor = newColor;
Debug.WriteLine(string.Format("@ cheerlights color is: {0}", _currentColor));
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
cheerlightsColorText.Text = _currentColor;
mainGrid.Background = new SolidColorBrush(_cheerlights.Colors[_currentColor].WindowsColor);
});
foreach (var lamp in _lampStateConsumers)
{
await SetLampColorAsync(lamp);
}
}
}