Exemple #1
0
        public async Task <bool> SwitchOffLight(Guid lightId)
        {
            var success = await _lightDriver.SwitchOffLight(lightId);

            var streetlightDetail = await _dataService.GetStreetlightDetail(lightId); // kills power to the light

            List <Task <bool> > tasks = new List <Task <bool> >();

            foreach (var bulb in streetlightDetail.Bulbs)
            {
                //await _dataService.UpdateBulbStatus(bulb.BulbInformation.Id, false); // shut off all bulbs without mercy
                tasks.Add(_dataService.UpdateBulbStatus(bulb.BulbInformation.Id, false));
            }

            await Task.WhenAll(tasks);

            await _dataService.UpdateStreetlightStatus(lightId, false);

            return(true);
        }
        public async Task <bool> SwitchOffLight(Guid lightId)
        {
            var success = await _lightDriver.SwitchOffLight(lightId);

            var streetlightDetail = await _dataService.GetStreetlightDetail(lightId); // kills power to the light

            try
            {
                var tasks      = new List <Task>();
                var countBulbs = streetlightDetail.Bulbs.Count();
                //foreach-loop uses more stack space for local variables compare with for-loop
                for (int i = 0; i < countBulbs; i++)
                {
                    int taskNo = i; // copy local for closure
                    var task   = new Task(() =>
                    {
                        _dataService.UpdateBulbStatus(streetlightDetail.Bulbs.ElementAt(taskNo).BulbInformation.Id, false); // shut off all bulbs without mercy
                    });
                    tasks.Add(task);

#if DEBUG
                    //To run synchronously for debugging uncomment following code
                    //task.RunSynchronously();
#endif
                    task.Start();
                }
                await Task.WhenAll(tasks);
            }
            catch (Exception e)
            {
                // catch this so that don't throw an exception
                // log and handle faulted tasks
            }

            await _dataService.UpdateStreetlightStatus(lightId, false);

            return(true);
        }