static void Main(string[] args) { const int sleepDurationInSeconds = 1000; // TaskFactory.StartNew() vs. Task.Run() ActionTimer.Time("TaskFactory.StartNew()", () => { Task factoryTask = Task.Factory.StartNew(() => Task.Delay(sleepDurationInSeconds)); Task.WaitAll(factoryTask); }); ActionTimer.Time("Task.Run()", () => { Task runTask = Task.Run(() => Task.Delay(sleepDurationInSeconds)); Task.WaitAll(runTask); }); // Disclaimer Console.WriteLine(Environment.NewLine + "Disclaimer:" + Environment.NewLine + "TaskFactory.StartNew() runs faster because Task.Run goes through a setup process for async/await. The task returned by TaskFactory.StartNew can not be used with async/await unless unwraped into an asynchronous operation with TaskExtensions.Unwrap()." + Environment.NewLine); // Task Cancellation ActionTimer.Time("Task Cancellation", () => { Console.WriteLine("Starting cancellable task which will run for 60 seconds if not cancelled (cancellation is set to occur after 3 seconds)."); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); Task cancelableTask = Pseudo.LongRunningCancellableTask(cancellationTokenSource.Token); cancellationTokenSource.CancelAfter(3000); cancelableTask.Wait(); }); // Async / Await AsyncAwaitConcepts(); Console.ReadLine(); }
public void Test_Recurring_Timer() { var timer = new ActionTimer(null, TimeSpan.FromSeconds(2), () => Debug.WriteLine("PING"), false, true); Thread.Sleep(TimeSpan.FromSeconds(30)); timer.Dispose(); }
public HeartbeatProcessor(ILog log, INatsClient natsClient, IBoshConfig config) { this.log = log; this.natsClient = natsClient; this.config = config; this.actionTimer = new ActionTimer(log, config.HeartbeatInterval, this.Beat, false, false); }
public override void update(ActionTimer timer) { if (mToNpc == 0) { //Startup.chat.MessageBox.addLine(new ColorRGBA(mR, mG, mB, mA), mMessage); ChatMessage message = new ChatMessage(null, null, ChatMessageType.PM, mMessage); message.Color = new ColorRGBA(mR, mG, mB, mA); NotificationManager.GetNotificationManager().DisplayNotification(message); completed = true; } else { Vob v = Player.getVob(mToNpc); if (v != null && v is Player) { //Startup.chat.MessageBox.addLine((Player)v, new ColorRGBA(mR, mG, mB, mA), mMessage); ChatMessage message = new ChatMessage(null, (Player)v, ChatMessageType.PM, mMessage); message.Color = new ColorRGBA(mR, mG, mB, mA); NotificationManager.GetNotificationManager().DisplayNotification(message); completed = true; } } isFinished = true; timer.removeAction(this); }
public void Init() { if (hasInitialized) return; hasInitialized = true; View = new WeenusUI(this); MenuAnimationTimer = new ActionTimer(MenuAnimationSpeed, OnMenuAnimationComplete); MenuAnimationTimer.AccurateMode = true; View.SetClickHandler("games", true, delegate () { View.UI.SwitchToScreen("games"); View.UI.CloseAppMenu(); }); View.SetClickHandler("friends", true, delegate () { View.UI.SwitchToScreen("friends"); View.UI.CloseAppMenu(); }); View.SetClickHandler("exit", true, delegate() { Application.Quit(); }); View.SetClickHandler("backtogame", true, delegate() { MobileUIManager.Current.Manager.StartPlayMode(); }); MenuBacking.onClick.AddListener(delegate() { this.CloseAppMenu(); }); }
public override async void OnNavigatedTo(INavigationParameters param) { if (Ds.NeedInit) { var path = AppFile.GetPath(); path = Path.Combine(path, AppUtils.DbName); await Ds.Init(path); } var runTimer5 = param?[nameof(NavParamEnum.RunTimer5)] as bool?; if (runTimer5 != null && (bool)runTimer5) { var objGameName = param?[nameof(NavParamEnum.GameName)]; if (objGameName != null) { _gameName = objGameName.ToString(); if (_timer == null) { _timer = new ActionTimer(); _timer.InitAndStart(ShowMess); } else { _timer.Restart(); } } } await InitGames(); }
private void ActionTime_Tick(object sender, EventArgs e) { if (CheckForUpdates()) { OpenA = Bridge.OpenA; P = Bridge.P; G = Bridge.G; Bridge.UpdatesForBob = false; PLbl.Text += P; GLbl.Text += G; OpenALbl.Text += OpenA; FirstStageBob(); secretKey = (int)BigInteger.ModPow(OpenA, b, P); KeyLbl.Text += secretKey; GetKeyHash(); HashLbl.Text += keyHash; Bridge.OpenB = OpenB; Bridge.LogLbl.Text += "Пользователь 2 отправляет остаток от деления - 'B' в открытом виде,\r\n а также хеш секрета Пользователю 1\r\n"; Bridge.LogLbl.Text += $"B={OpenB}\r\n"; Bridge.LogLbl.Text += $"ХЕШ={keyHash}\r\n"; Bridge.LogLbl.Text += $"{new string('-', 50)}\r\n"; Bridge.BobsHash = keyHash; Bridge.UpdatesForAlice = true; ActionTimer.Stop(); DecryptBtn.Enabled = true; EncryptBtn.Enabled = true; } }
public void AddDelayedAction(Action action, float deltaTimeSeconds) { var actionTimer = new ActionTimer(action, deltaTimeSeconds); actionTimer.Start(); _activeTimers.Add(actionTimer); }
private void ActionResult(string result) { LblAction.Text = result; LblAction.Visible = true; ActionTimer.Start(); RefreshEnabledButtons(); }
public override void update(ActionTimer timer) { List <Account> _list = new List <Account>(); using (SQLiteCommand command = new SQLiteCommand(Sqlite.getSqlite().connection)) { command.CommandText = "SELECT id, name FROM `account`"; using (SQLiteDataReader sdrITM = command.ExecuteReader()) { if (sdrITM.HasRows) { while (sdrITM.Read()) { int accID = Convert.ToInt32(sdrITM["id"]); string name = Convert.ToString(sdrITM["name"]); _list.Add(new Account() { accountID = accID, name = name }); } } } } list = _list.ToArray(); isFinished = true; timer.removeAction(this); }
public static void Test(string input) { int minuteDelay = 10; WorldServer.Instance.OnClients(x => x.Character.Notification("Pour des raisons de maintenance, le serveur va être redémarré dans " + minuteDelay + " minutes. Merci de votre compréhension.")); ActionTimer action = new ActionTimer((minuteDelay * 60000) / 2, new Action(() => { WorldServer.Instance.OnClients(x => x.Character.Notification("Pour des raisons de maintenance, le serveur va être redémarré dans " + minuteDelay / 2 + " minutes. Merci de votre compréhension.")); }), false); action.Start(); action = new ActionTimer(minuteDelay * 60000, new Action(() => { SaveTask.Save(); Environment.Exit(0); }), false); action.Start(); }
static void Main(string[] args) { using (var timer = new ActionTimer(time => Console.WriteLine(time.TotalSeconds))) { Console.WriteLine("Hello World!"); } }
public void CompileAllModels() { if (_constants.Debug) { _logger.Log(LogType.Debug, $"Attempting to compile {_definitions.Count} d2o models to C# class..."); } var elapsedCompiling = ActionTimer.Bench(() => { foreach (var file in _files) { foreach (var classDef in file.LocalClassDefinitions.Unpacked) { var elapsed = ActionTimer.Bench(() => new D2OModelCompiler(file.LocalClassDefinitions.Unpacked, classDef).Compile()); if (_constants.Debug) { _logger.Log(LogType.Debug, $"{classDef.Name}.cs successfully compiled in {elapsed.Milliseconds}ms"); } } } }); _logger.Log(LogType.Info, $"{_definitions.Count} d2o models succcessfully compiled to C# class in {elapsedCompiling.Milliseconds}ms"); }
public UIScreenManager() { TransitionTimer = new ActionTimer(0.25f, CompleteTransition); TransitionTimer.AccurateMode = true; rotateRight = Quaternion.Euler(new Vector3(0, 30, 0)); rotateLeft = Quaternion.Euler(new Vector3(0, 330, 0)); }
public ChatFormBob(BridgeForm bf) { InitializeComponent(); Bridge = bf; ActionTimer.Start(); DecryptBtn.Enabled = false; EncryptBtn.Enabled = false; }
/// <summary> /// 下一帧的LateUpdate中触发 /// </summary> /// <param name="action"></param> public static void NextFrame(Action action) { if (action != null) { var item = ActionTimer.Create(action); item.RestFrame = 1; Instance._actionTimers.Add(item.Id, item); } }
public void Connected() { AppStart = DateTime.Now; SendAppState(UnityAppState.CONNECTED); AppState = UnityAppState.RUNNING; Log.Success("Simulation App is now connected!"); statisticsService.InitializeStatisticsService(); StateUpdater = new ActionTimer(() => SendAppState(), new TimeSpan(0, 0, 5)); }
public void EnsureLootTimer() { if (showTimer != null) return; showTimer = new ActionTimer(0.15f, delegate() { this.Parent.rect.Set(0, 0, Screen.width, Screen.height); }); }
public DropItem(CharacterItemRecord record, ushort quantity, ushort cellid, AbstractMapInstance map) { this.Id = map.PopNextDropItemId(); this.Record = record; this.Map = map; this.CellId = cellid; this.Quantity = quantity; Timer = new ActionTimer(900000, Remove, false); PickedUp = false; }
public void Light() { if (this._lit || this.ammo <= 0) { return; } this._lit = true; this._litTimer = (ActionTimer)0.03f; this._litStartTimer = new ActionTimer(0.01f, reset: false); this._burnSound = SFX.Play("fuseBurn", 0.5f, looped: true); }
static public void initiateFingerStatus() { // SETTINGS // thumbOnOffTimer = new ActionTimer(3); thumbCursorTimer = new ActionTimer(3); // indexCursorTimer = new ActionTimer(3); middleRollTimer = new ActionTimer(10); indexClickTimer = new ActionTimer(105, 190); middleClickTimer = new ActionTimer(105, 190); return; }
public override void update(ActionTimer timer) { using (SQLiteCommand command = new SQLiteCommand(Sqlite.getSqlite().connection)) { command.CommandText = "SELECT name FROM `account` WHERE `id`=@id"; command.Parameters.AddWithValue("@id", this.accID); using (SQLiteDataReader sdrITM = command.ExecuteReader()) { if (sdrITM.HasRows) { sdrITM.Read(); this.name = Convert.ToString(sdrITM["name"]); accExists = true; } } } if (accExists) { using (SQLiteCommand command = new SQLiteCommand(Accounts.Logs.SQLiteLogger.connection)) { command.CommandText = "SELECT * FROM `logStats` WHERE `accountID`=@id"; command.Parameters.AddWithValue("@id", this.accID); using (SQLiteDataReader sdrITM = command.ExecuteReader()) { if (sdrITM.HasRows) { List <AccountLogChar> alcList = new List <AccountLogChar>(); while (sdrITM.Read()) { AccountLogChar alc = new AccountLogChar(); alc.type = Convert.ToInt32(sdrITM["type"]); alc.value = Convert.ToInt32(sdrITM["value"]); alc.time = Convert.ToInt64(sdrITM["time"]); alcList.Add(alc); } charStatList = alcList.ToArray(); } } } } isFinished = true; timer.removeAction(this); }
private void InitializeDrawElements() { var itemDescriptor = GuiSystem.GetSkinItemDescriptor <TextBoxSkinItemDescriptor>(); _border = new NinePatchSprite(itemDescriptor.SkinTexture, itemDescriptor.NormalRectangle, itemDescriptor.Border); _spriteText = new SpriteText(itemDescriptor.NormalFont); _spriteText.HorizontalAlignment = HorizontalAlignment.Left; _cursorAnimatorTimer = new ActionTimer(OnCursorAnimateTick, 0.5f, true); _cursorAnimatorTimer.Start(); _inputController = new StringInputController(InputType.AlphaNumeric); }
// Use this for initialization void Start() { if (DestoryObject) { timer = new ActionTimer(TimeToExpire, ExpireSelf); } else { timer = new ActionTimer(TimeToExpire, DisableSelf); } timer.Reset(); timer.Start(); }
protected override void PreInitialize(ServiceProvider provider) { base.PreInitialize(provider); this.Inline = InlineType.None; provider.Service(out _graphics); provider.Service(out _window); provider.Service(out _spriteBatch); _carret = _graphics.BuildPixel(); _carretTimer = new ActionTimer(750); this.OnState[ElementState.Focused] += this.HandleFocused; }
// Start is called before the first frame update void Start() { OBJ_POOLER = ObjectPoolController.SharedInstance; OBJ_POOLER.CreateObjPool(PLAYER_PROJECTILE_POOL_NAME, bulletPrefabs[0], true); _EC.SetVelocityFunctions(OverrideVelocities, CompoundVelocities, MultiplyVelocities); _EC.SetEventFunctions(OnLanding, WhileInAir); jumps = maxJumps; dashAction = gameObject.AddComponent <ActionTimer>(); dashAction.Init(null, EndDash, dashTime, dashCooldown, 0f); attackAction = gameObject.AddComponent <ActionTimer>(); attackAction.Init(null, null, 0f, 0f, 0f); swingHitbox.SetActive(false); heatUIEffect.SetMax(maxHeat); _EC.faction = FactionList.PLAYER; }
public ChatFormAlice(BridgeForm bf) { InitializeComponent(); primeNumbers = new List <int> { 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911 }; ActionTimer.Start(); Bridge = bf; DecryptBtn.Enabled = false; EncryptBtn.Enabled = false; }
public override void update(ActionTimer timer) { NPCProto[] _list = World.getWorld("NEWWORLD\\NEWWORLD.ZEN").getNPCList(); list = new NPCCOPYED[_list.Length]; for (int i = 0; i < list.Length; i++) { list[i] = new NPCCOPYED() { name = _list[i].Name, position = new Vec3f(_list[i].Position), IsPlayer = (_list[i] is Player) ? true : false }; } isFinished = true; timer.removeAction(this); }
public MemoryCell(Random rSeed, Context.SEAContext.DoHandler doCallback, ref StringBuilder key) { id = MyId.NewId(rSeed.Next()); cell = new StringBuilder(CELL_LENGHT, CELL_LENGHT); id.AppendTo(ref key); id.AppendTo(ref cell); cell.Append(FLAG_VOID); id.AppendTo(ref cell); cell.Length = CELL_LENGHT; this.doCommand = doCallback; reader = new Reader(); writer = new Writer(); listener = new ActionTimer(); listener.Start(Translate); }
public static void Fight() // ajout de la notification delai avec le timer { var guilds = GuildArenaRecord.GuildsArena.Take(GuildArenaRecord.GuildsArena.Count / 2); foreach (var guild in guilds.ToArray()) { var clients = WorldServer.Instance.GetOnlineClients().FindAll(x => x.Character.Guild.Id == guild.FirstGuildId || x.Character.Guild.Id == guild.SecondGuildId); foreach (var client in clients) { client.SendRaw(RawDataManager.GetRawData("gvgtimer")); } guild.RemoveElement(); } ActionTimer timer = new ActionTimer(MINUTES_BEFORE_GVG_START * 60000, StartFighting, false); timer.Start(); }
private void ActionTimer_Tick(object sender, EventArgs e) { if (CheckForUpdates() || currentStage == AlicesStages.First) { switch (currentStage) { case AlicesStages.First: FirstStageAlice(); Bridge.OpenA = OpenA; Bridge.P = P; Bridge.G = G; Bridge.LogLbl.Text += $"Пользователь 1 отправляет остаток от деления - 'A' в открытом виде,\r\n а также пару чисел 'p' и 'g' Пользователю 2\r\n"; Bridge.LogLbl.Text += $"A={OpenA}\r\np={P}\r\ng={G}\r\n"; Bridge.LogLbl.Text += $"{new string('-', 50)}\r\n"; Bridge.UpdatesForBob = true; currentStage = AlicesStages.Second; break; case AlicesStages.Second: SecondStageAlice(); KeyLbl.Text += secretKey; Bridge.UpdatesForAlice = false; if (!KeyHash.Equals(Bridge.BobsHash)) { Bridge.LogLbl.Text += "Пользователь 1 отклоняет хеш Пользователя 2\r\n"; } else { Bridge.LogLbl.Text += "Пользователь 1 подтверждает хеш Пользователя 2\r\n"; } Bridge.LogLbl.Text += $"{new string('-', 50)}\r\n"; ActionTimer.Stop(); DecryptBtn.Enabled = true; EncryptBtn.Enabled = true; break; default: throw new Exception(); } } }
public void UseStated(Character character) { this.Character = character; CharacterJob job = Character.GetJob(Skill.Template.ParentJobIdEnum); if (job != null && job.Level < Skill.Template.MinLevel) { return; } if (State == StatedElementStatesType.Active) { this.Character.Collecting = true; this.UpdateState(StatedElementStatesType.Used); this.GrowCallback = new ActionTimer(GrowInterval * 1000, Grow, false); OnUsedCallback = new Timer(Skill.Template.Duration * 100); OnUsedCallback.Elapsed += OnUsedCallback_Elapsed; OnUsedCallback.Start(); } }
public void StartCountdown(float time, Action action) { if (timer == null) { timer = new ActionTimer(time, () => { if (action != null) { action(); } this.gameObject.SetActive(false); HamburglarContext.Instance.WaitingForPlayersDisplay.gameObject.SetActive(false); }); } timer.AccurateMode = true; timer.TimeLimit = time; timer.Reset(); timer.Start(); this.gameObject.SetActive(true); }
public void EndAction() { m_IdleRounds = 0; if (m_ActionTimer != null) { m_ActionTimer.Stop(); m_ActionTimer = null; } }
public TutorialOpenDoor() { timer = new ActionTimer(3, OpenRandomDoor); }
public SwipeHelper() { SwiperTimer = new ActionTimer(0.25f, DetermineSwipe); SwiperTimer.AccurateMode = true; }
public void BeginAction(PokerDealer dealer) { if (m_ActionTimer != null) { m_ActionTimer.Stop(); m_ActionTimer = null; } m_ActionTimer = new ActionTimer(dealer, this); }
public void SetFloatingMessage(string message, Color color) { if (floatingMessageTimer == null) { floatingMessageTimer = new ActionTimer(minTimeBetweenMessages, () => { if (floatingMessageQueue.Count > 0) CheckFloatingMessageQueue(); }); floatingMessageTimer.Loop = true; floatingMessageTimer.Reset(); floatingMessageTimer.Start(); } floatingMessageQueue.Enqueue(new QueuedFloatingMessage() { Color = color, Message = message }); if ((Time.realtimeSinceStartup - lastMessageSpawned) > minTimeBetweenMessages) { // clear immediately if no other active messages floatingMessageTimer.Reset(); CheckFloatingMessageQueue(); } }
void Start() { timer = new ActionTimer(AnimationTime, AnimationFinished); rect = GetComponent<RectTransform>(); LeftButton.GetComponentInChildren<Button>().onClick.AddListener(() => { HandleTrapButtonClick(false); }); RightButton.GetComponentInChildren<Button>().onClick.AddListener(() => { HandleTrapButtonClick(true); }); leftButtonInitialPosition = LeftButton.anchoredPosition; rightButtonInitialPosition = RightButton.anchoredPosition; hasStarted = true; }