Exemplo n.º 1
0
        private async void btnGo_Click(object sender, EventArgs e)
        {
            tbVehiclesStats.Text = Statistics.GetResult(Statistics.RaceCondition.start);
            await Task.Run(() => {
                if (vehicles.Count != 0)
                {
                    Invoke((MethodInvoker) delegate {
                        nudDistance.Enabled      = false;
                        btnGo.Enabled            = false;
                        btnRemoveVehicle.Enabled = false;
                        btnAddVehicle.Enabled    = false;
                    });
                    var raceCondition = new RaceCondition();
                    raceCondition.RaceConditionIsChanged += DisplayChangedRaceCondition;
                    raceCondition.StartRace();
                    tbRacingStats.Invoke((MethodInvoker) delegate { tbRacingStats.Text += "Гонка завершена!"; });
                    Invoke((MethodInvoker) delegate {
                        nudDistance.Enabled      = true;
                        btnGo.Enabled            = true;
                        btnRemoveVehicle.Enabled = true;
                        btnAddVehicle.Enabled    = true;
                    });
                }
            });

            DisplayReport();
        }
Exemplo n.º 2
0
        public async Task <bool> ReleaseLockAsync(string key)
        {
            await RaceCondition.RunAsync(async() =>
            {
                await Cache.LockReleaseAsync(new RedisKey(key), new RedisValue(FixedValue));
            }, key).NoContext();

            return(true);
        }
Exemplo n.º 3
0
        private async Task SumAsync2(int v, string key)
        {
            Func <Task> action = async() => await CountAsync(v);

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

            for (int i = 0; i < 20; i++)
            {
                tasks.Add(RaceCondition.RunAsync(action, key));
            }
            await Task.WhenAll(tasks);
        }
Exemplo n.º 4
0
 public static string GetResult(RaceCondition raceCondition)
 {
     if (raceCondition == RaceCondition.start)
     {
         finishers = new List <Vehicle>();
         string _vehicles = "";
         for (int i = 0; i < vehicles.Count; i++)
         {
             _vehicles += vehicles[i].ToString() + " - под номером " + (i + 1) + ";" + Environment.NewLine;
         }
         return("В гонке учавствуют " + vehicles.Count + " транспортных средств(а):" + Environment.NewLine
                + Environment.NewLine + _vehicles);
     }
     else if (raceCondition == RaceCondition.continues)
     {
         UpdateFinishersList();
         string _stats = "Статистика участников: " + Environment.NewLine + Environment.NewLine;
         for (int i = 0; i < vehicles.Count; i++)
         {
             if (vehicles[i].RemainingDistanceToFinish == 0)
             {
                 _stats += "Участник с номером " + (i + 1) + " финишировал;";
             }
             else
             {
                 _stats += "Участник с номером " + (i + 1) + " проехал "
                           + (100 - (vehicles[i].RemainingDistanceToFinish / Parameters.DistanceUnits * 100)).ToString("0.00")
                           + "% пути;";
             }
             if (vehicles[i].GetDowntime() > 0)
             {
                 _stats += " У него проколото колесо;";
             }
             _stats += Environment.NewLine;
         }
         return(_stats);
     }
     else if (raceCondition == RaceCondition.finish)
     {
         string _stats = "Статистика участников: " + Environment.NewLine + Environment.NewLine;
         for (int i = 0; i < vehicles.Count; i++)
         {
             _stats += "Участник с номером " + (i + 1) + ", " + vehicles.ToString()
                       + " финишировал на позиции " + (finishers.IndexOf(vehicles[i]) + 1) + ", зататив "
                       + vehicles[i].CountOfTimeUnits + " единиц времени;";
         }
         return(_stats);
     }
     return("");
 }
Exemplo n.º 5
0
        public async Task <bool> AcquireLockAsync(string key, TimeSpan expiringTime = default)
        {
            try
            {
                if (expiringTime == default)
                {
                    expiringTime = TimeSpan.FromSeconds(10);
                }
                RaceConditionResponse response = await RaceCondition.RunAsync(async() =>
                {
                    await Cache.LockTakeAsync(new RedisKey(key), new RedisValue(FixedValue), expiringTime);
                }, key).NoContext();

                return(response.IsExecuted && !response.InException);
            }
            catch
            {
                return(false);
            }
        }
Exemplo n.º 6
0
        public void StartGame()
        {
            int tempIndex = -1;

            RaceCondition?.Invoke("Race has been started!");
            while (!IsFinished)
            {
                ShowCarsCondition();
                foreach (var car in _cars)
                {
                    Drive drive = car.Drive;
                    tempIndex = drive();
                    if (tempIndex != -1)
                    {
                        break;
                    }
                }
                Thread.Sleep(1000);
                Console.Clear();
            }
            FinishRace(tempIndex - 1);
        }
        public void CheckThatTheSessionManangerDoesEndInARaceCondition(int latency, int updateCount)
        {
            var sessions = new[] {
                new Session {
                    Key = Guid.NewGuid().ToString()
                },
                new Session {
                    Key = Guid.NewGuid().ToString()
                }
            };
            var sessionManager = Substitute.For <ISessionManager>();

            var testClass = new RaceCondition(sessionManager);
            var tasks     = new List <Task>();

            sessionManager.Get(Arg.Any <string>())
            .Returns(info => new Session {
                Key = (string)info[0], Count = sessions.Single(s => s.Key == (string)info[0]).Count
            });
            sessionManager
            .When(x => x.Set(Arg.Any <ISession>()))
            .Do(info =>
            {
                Thread.Sleep(latency);
                sessions.Single(t => t.Key == ((ISession)info[0]).Key).Count = ((ISession)info[0]).Count;
            });

            foreach (var session in sessions)
            {
                for (int i = 0; i < updateCount; i++)
                {
                    tasks.Add(Task.Run(() => testClass.UpdateSession(session.Key)));
                }
            }

            Task.WaitAll(tasks.ToArray());
            Assert.IsTrue(sessions.All(s => s.Count == updateCount));
        }
Exemplo n.º 8
0
 public void FinishRace(int id)
 {
     Console.Clear();
     ShowWinner(id);
     RaceCondition?.Invoke("Race has been finished");
 }