System.Diagnostics.Stopwatch.Restart()

Here are the examples of the csharp api System.Diagnostics.Stopwatch.Restart() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1223 Examples 7

19 View Source File : Program.cs
License : MIT License
Project Creator : 0x1000000

private static async Task ExecScenarioAll(IScenario scenario, string msSqlConnectionString, string pgSqlConnectionString, string mySqlConnectionString)
        {
            Stopwatch stopwatch = new Stopwatch();

            Console.WriteLine();
            Console.WriteLine("-MS SQL Test-------");
            stopwatch.Restart();
            await ExecMsSql(scenario, msSqlConnectionString);
            stopwatch.Stop();
            Console.WriteLine($"-MS SQL Test End: {stopwatch.ElapsedMilliseconds} ms");

            Console.WriteLine("-Postgres Test-----");
            stopwatch.Start();
            await ExecNpgSql(scenario, pgSqlConnectionString);
            stopwatch.Stop();
            Console.WriteLine($"-Postgres Test End: {stopwatch.ElapsedMilliseconds} ms");

            Console.WriteLine();
            Console.WriteLine("-MY SQL Test-------");
            stopwatch.Restart();
            await ExecMySql(scenario, mySqlConnectionString);
            stopwatch.Stop();
            Console.WriteLine($"-MY SQL Test End: {stopwatch.ElapsedMilliseconds} ms");
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Main(string[] args)
        {
            //预热
            cli.Set(Guid.NewGuid().ToString(), "我也不知道为什么刚刚好十五个字");
            sedb.StringSet(Guid.NewGuid().ToString(), "我也不知道为什么刚刚好十五个字");

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            for (int i = 0; i < 10000; i++)
            {
                var tmp = Guid.NewGuid().ToString();
                cli.Set(tmp, "我也不知道为什么刚刚好十五个字");
                var val = cli.Get(tmp);
                if (val != "我也不知道为什么刚刚好十五个字") throw new Exception("not equal");
            }

            stopwatch.Stop();
            Console.WriteLine("FreeRedis:"+stopwatch.ElapsedMilliseconds);

            //stopwatch.Restart();
            // csredis 会出现连接不能打开的情况
            //for (int i = 0; i < 100; i++)
            //{
            //    var tmp = Guid.NewGuid().ToString();
            //    csredis.Set(tmp, "我也不知道为什么刚刚好十五个字");
            //    _ = csredis.Get(tmp);
            //}

            //stopwatch.Stop();
            //Console.WriteLine("csredis:" + stopwatch.ElapsedMilliseconds);

            stopwatch.Restart();

            for (int i = 0; i < 10000; i++)
            {
                var tmp = Guid.NewGuid().ToString();
                sedb.StringSet(tmp, "我也不知道为什么刚刚好十五个字");
                var val = sedb.StringGet(tmp);
                if (val != "我也不知道为什么刚刚好十五个字") throw new Exception("not equal");
            }

            stopwatch.Stop();
            Console.WriteLine("Seredis:" + stopwatch.ElapsedMilliseconds);

            cli.Subscribe("abc", (chan, msg) =>
            {
                Console.WriteLine($"FreeRedis {chan} => {msg}");
            });

            seredis.GetSubscriber().Subscribe("abc", (chan, msg) =>
            {
                Console.WriteLine($"Seredis {chan} => {msg}");
            });
            Console.ReadKey();

            return;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Select(StringBuilder sb, int forTime, int size) {
			Stopwatch sw = new Stopwatch();
			sw.Restart();
			for (var a = 0; a < forTime; a++)
				fsql.Select<Song>().Limit(size).ToList();
			sw.Stop();
			sb.AppendLine($"FreeSql Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");

			sw.Restart();
			for (var a = 0; a < forTime; a++)
				sugar.Queryable<Song>().Take(size).ToList();
			sw.Stop();
			sb.AppendLine($"SqlSugar Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");

			sw.Restart();
			for (var a = 0; a < forTime; a++) {
				using (var db = new SongContext()) {
					db.Songs.Take(size).AsNoTracking().ToList();
				}
			}
			sw.Stop();
			sb.AppendLine($"EFCore Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Update(StringBuilder sb, int forTime, int size) {
			Stopwatch sw = new Stopwatch();

			var songs = fsql.Select<Song>().Limit(size).ToList();
			sw.Restart();
			for (var a = 0; a < forTime; a++) {
				fsql.Update<Song>().SetSource(songs).ExecuteAffrows();
			}
			sw.Stop();
			sb.AppendLine($"FreeSql Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");

			songs = sugar.Queryable<Song>().Take(size).ToList();
			sw.Restart();
			Exception sugarEx = null;
			try {
				for (var a = 0; a < forTime; a++)
					sugar.Updateable(songs).ExecuteCommand();
			} catch (Exception ex) {
				sugarEx = ex;
			}
			sw.Stop();
			sb.AppendLine($"SqlSugar Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : ""));

			using (var db = new SongContext()) {
				songs = db.Songs.Take(size).AsNoTracking().ToList();
			}
			sw.Restart();
			for (var a = 0; a < forTime; a++) {

				using (var db = new SongContext()) {
					//db.Configuration.AutoDetectChangesEnabled = false;
					db.Songs.UpdateRange(songs.ToArray());
					db.SaveChanges();
				}
			}
			sw.Stop();
			sb.AppendLine($"EFCore Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Insert(StringBuilder sb, int forTime, int size) {
			var songs = Enumerable.Range(0, size).Select(a => new Song {
				Create_time = DateTime.Now,
				Is_deleted = false,
				replacedle = $"Insert_{a}",
				Url = $"Url_{a}"
			});

			//预热
			fsql.Insert(songs.First()).ExecuteAffrows();
			sugar.Insertable(songs.First()).ExecuteCommand();
			using (var db = new SongContext()) {
				//db.Configuration.AutoDetectChangesEnabled = false;
				db.Songs.AddRange(songs.First());
				db.SaveChanges();
			}
			Stopwatch sw = new Stopwatch();

			sw.Restart();
			for (var a = 0; a < forTime; a++) {
				fsql.Insert(songs).ExecuteAffrows();
			}
			sw.Stop();
			sb.AppendLine($"FreeSql Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");

			sw.Restart();
			for (var a = 0; a < forTime; a++) {
				using (var db = new FreeSongContext()) {
					db.Songs.AddRange(songs.ToArray());
					db.SaveChanges();
				}
			}
			sw.Stop();
			sb.AppendLine($"FreeSql.DbContext Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");

			sw.Restart();
			Exception sugarEx = null;
			try {
				for (var a = 0; a < forTime; a++)
					sugar.Insertable(songs.ToArray()).ExecuteCommand();
			} catch (Exception ex) {
				sugarEx = ex;
			}
			sw.Stop();
			sb.AppendLine($"SqlSugar Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : ""));

			sw.Restart();
			for (var a = 0; a < forTime; a++) {

				using (var db = new SongContext()) {
					//db.Configuration.AutoDetectChangesEnabled = false;
					db.Songs.AddRange(songs.ToArray());
					db.SaveChanges();
				}
			}
			sw.Stop();
			sb.AppendLine($"EFCore Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
		}

19 View Source File : RequestMiddleware.cs
License : Apache License 2.0
Project Creator : 91270

public async Task InvokeAsync(HttpContext context)
        {
            // 过滤,只有接口
            if (context.Request.Path.Value.ToLower().Contains("api"))
            {
                context.Request.EnableBuffering();
                Stream originalBody = context.Response.Body;

                _stopwatch.Restart();

                // 获取 Api 请求内容
                var requestContent = await GetRequesContent(context);


                // 获取 Api 返回内容
                using (var ms = new MemoryStream())
                {
                    context.Response.Body = ms;

                    await _next(context);
                    ms.Position = 0;

                    await ms.CopyToAsync(originalBody);
                }

                context.Response.Body = originalBody;

                _stopwatch.Stop();

                var eventInfo = new LogEventInfo();
                eventInfo.Message = "Success";
                eventInfo.Properties["Elapsed"] = _stopwatch.ElapsedMilliseconds;
                eventInfo.Properties["RequestBody"] = requestContent;

                logger.Trace(eventInfo);
            }
            else
            {
                await _next(context);
            }
        }

19 View Source File : MouseWatcher.cs
License : MIT License
Project Creator : a1xd

public void ReadMouseMove(Message message)
        {
            RawInput rawInput;
            int size = Marshal.SizeOf(typeof(RawInput));
            _ = GetRawInputData(message.LParam, RawInputCommand.Input, out rawInput, ref size, Marshal.SizeOf(typeof(RAWINPUTHEADER)));

            bool relative = !rawInput.Data.Mouse.Flags.HasFlag(RawMouseFlags.MoveAbsolute);

            bool deviceMatch = false;
            foreach (var (handle, normalized) in SettingsManager.ActiveNormTaggedHandles)
            {
                if (handle == rawInput.Header.Device)
                {
                    deviceMatch = true;

                    if (normalized != LastMoveNormalized)
                    {
                        LastMoveDisplayFormat = normalized ?
                                                Constants.MouseMoveNormalizedFormat :
                                                Constants.MouseMoveDefaultFormat;
                        LastMoveNormalized = normalized;
                    }

                    break;
                }
            }

            if (relative && deviceMatch && (rawInput.Data.Mouse.LastX != 0 || rawInput.Data.Mouse.LastY != 0))
            {
                var time = Stopwatch.Elapsed.TotalMilliseconds;
                Stopwatch.Restart();
                time = time > 100 ? 100 : time;
                time = time > (PollTime * 0.8) ? time : (PollTime * 0.8);

                double x = rawInput.Data.Mouse.LastX;
                double y = rawInput.Data.Mouse.LastY;

                // strip negative directional multipliers, charts calculated from positive input

                Vec2<double> dirMults = new Vec2<double>
                {
                    x = SettingsManager.ActiveProfile.lrSensRatio,
                    y = SettingsManager.ActiveProfile.udSensRatio
                };

                if (dirMults.x > 0 && x < 0)
                {
                    x /= dirMults.x;
                }

                if (dirMults.y > 0 && y < 0)
                {
                    y /= dirMults.y;
                }

                MouseData.Set(rawInput.Data.Mouse.LastX, rawInput.Data.Mouse.LastY);
                AccelCharts.MakeDots(x, y, time);
            }

        }

19 View Source File : Load500x500SeriesRefreshTest.xaml.cs
License : MIT License
Project Creator : ABTSoftware

public void Execute(TestParameters testParameters, TimeSpan duration, Action<double> fpsResult)
        {
            int pointCount = testParameters.PointCount;
            int seriesCount = testParameters.PointCount;

            DataSeries = null;

            using (sciChart.SuspendUpdates())
            {
                // Generate Data and mark time                 
                XyData[] xyData = new XyData[seriesCount];
                var random = new Random();
                for (int i = 0; i < seriesCount; i++)
                {
                    var generator = new RandomWalkGenerator(random.Next(0, int.MaxValue));
                    xyData[i] = generator.GetRandomWalkSeries(pointCount);
                }

                // Append to SciChartSurface 
                var allDataSeries = new IDataSeries[seriesCount];
                for (int i = 0; i < seriesCount; i++)
                {
                    var dataSeries = new XyDataSeries<double, double>() {DataDistributionCalculator = d};
                    dataSeries.Append(xyData[i].XData, xyData[i].YData);
                    allDataSeries[i] = dataSeries;
                }
                DataSeries = allDataSeries;
                LineSeriesSource.SetStrokeThickness(sciChart, testParameters.StrokeThickness);
                LineSeriesSource.SetAntiAliasing(sciChart, testParameters.AntiAliasing);
                LineSeriesSource.SetDataSeries(sciChart, allDataSeries);

                sciChart.ZoomExtents();

                // Run test (just refresh)
                //int inc = 1;
            }

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Restart();
      
            if (testParameters.TestRunner == TestRunnerType.Composition)
                _testRunner = new CompositionTestRunner(duration, () =>
                {

                    // Make small changes to the YAxis Visible Range to trigger an update and cause some rescaling
                    //var currentRange = this.sciChart.YAxis.VisibleRange.AsDoubleRange();
                    
                    double dY = (double)sw.ElapsedMilliseconds/1000.0;
                    this.sciChart.YAxis.VisibleRange = new DoubleRange(-40 - dY, 40 + dY); 
                    //this.sciChart.YAxis.VisibleRange.SetMinMax(-1 - dY, 1 + dY); 
                    //inc = -inc;
                }, fpsResult);
            else
                _testRunner = new DispatcherTimerRunner(duration, () =>
                {

                    // Make small changes to the YAxis Visible Range to trigger an update and cause some rescaling
                    //var currentRange = this.sciChart.YAxis.VisibleRange.AsDoubleRange();
                    //this.sciChart.YAxis.VisibleRange = new DoubleRange(currentRange.Min - RangeIncrement, currentRange.Max + RangeIncrement);
                    
                    //If not setting large scale enough, SciChart crashes randomly. (-30 ... 30) is not enough 
                    double dY = (double)sw.ElapsedMilliseconds / 1000.0;
                    this.sciChart.YAxis.VisibleRange = new DoubleRange(-40 - dY, 40 + dY); 
                    //inc = -inc;
                }, fpsResult);


            sciChart.Rendered += _testRunner.OnSciChartRendered;
            _testRunner.Run();
        }

19 View Source File : RateMonitor.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void Restart()
        {
            stopwatch.Restart();
        }

19 View Source File : RateLimiter.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void RegisterEvent()
        {
            numberOfEventsRegistered++;

            var elapsedSeconds = stopwatch.Elapsed.TotalSeconds;

            if (numberOfEventsRegistered > maxNumberOfEvents || elapsedSeconds > overPeriodInSeconds)
            {
                numberOfEventsRegistered = 1;

                stopwatch.Restart();
            }
        }

19 View Source File : WorldManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void UpdateWorld()
        {
            log.DebugFormat("Starting UpdateWorld thread");

            WorldActive = true;
            var worldTickTimer = new Stopwatch();

            while (!pendingWorldStop)
            {
                /*
                When it comes to thread safety for Landblocks and WorldObjects, ACE makes the following replacedumptions:

                 * Inbound ClientMessages and GameActions are handled on the main UpdateWorld thread.
                   - These actions may load Landblocks and modify other WorldObjects safely.

                 * PlayerEnterWorld queue is run on the main UpdateWorld thread.
                   - These actions may load Landblocks and modify other WorldObjects safely.

                 * Landblock Groups (calculated by LandblockManager) can be processed in parallel.

                 * Adjacent Landblocks will always be run on the same thread.

                 * Non-adjacent landblocks might be run on different threads.
                   - If two non-adjacent landblocks both touch the same landblock, and that landblock is active, they will be run on the same thread.

                 * Database results are returned from a task spawned in SerializedShardDatabase (via callback).
                   - Minimal processing should be done from the callback. Return as quickly as possible to let the database thread do database work.
                   - The processing of these results should be queued to an ActionQueue

                 * The only cases where it's acceptable for to create a new Task, Thread or Parallel loop are the following:
                   - Every scenario must be one where you don't care about breaking ACE
                   - DeveloperCommand Handlers
                */

                worldTickTimer.Restart();

                ServerPerformanceMonitor.RestartEvent(ServerPerformanceMonitor.MonitorType.PlayerManager_Tick);
                PlayerManager.Tick();
                ServerPerformanceMonitor.RegisterEventEnd(ServerPerformanceMonitor.MonitorType.PlayerManager_Tick);

                ServerPerformanceMonitor.RestartEvent(ServerPerformanceMonitor.MonitorType.NetworkManager_InboundClientMessageQueueRun);
                NetworkManager.InboundMessageQueue.RunActions();
                ServerPerformanceMonitor.RegisterEventEnd(ServerPerformanceMonitor.MonitorType.NetworkManager_InboundClientMessageQueueRun);

                // This will consist of PlayerEnterWorld actions, as well as other game world actions that require thread safety
                ServerPerformanceMonitor.RestartEvent(ServerPerformanceMonitor.MonitorType.actionQueue_RunActions);
                ActionQueue.RunActions();
                ServerPerformanceMonitor.RegisterEventEnd(ServerPerformanceMonitor.MonitorType.actionQueue_RunActions);

                ServerPerformanceMonitor.RestartEvent(ServerPerformanceMonitor.MonitorType.DelayManager_RunActions);
                DelayManager.RunActions();
                ServerPerformanceMonitor.RegisterEventEnd(ServerPerformanceMonitor.MonitorType.DelayManager_RunActions);

                ServerPerformanceMonitor.RestartEvent(ServerPerformanceMonitor.MonitorType.UpdateGameWorld);
                var gameWorldUpdated = UpdateGameWorld();
                ServerPerformanceMonitor.RegisterEventEnd(ServerPerformanceMonitor.MonitorType.UpdateGameWorld);

                ServerPerformanceMonitor.RestartEvent(ServerPerformanceMonitor.MonitorType.NetworkManager_DoSessionWork);
                int sessionCount = NetworkManager.DoSessionWork();
                ServerPerformanceMonitor.RegisterEventEnd(ServerPerformanceMonitor.MonitorType.NetworkManager_DoSessionWork);

                ServerPerformanceMonitor.Tick();

                // We only relax the CPU if our game world is able to update at the target rate.
                // We do not sleep if our game world just updated. This is to prevent the scenario where our game world can't keep up. We don't want to add further delays.
                // If our game world is able to keep up, it will not be updated on most ticks. It's on those ticks (between updates) that we will relax the CPU.
                if (!gameWorldUpdated)
                    Thread.Sleep(sessionCount == 0 ? 10 : 1); // Relax the CPU more if no sessions are connected

                Timers.PortalYearTicks += worldTickTimer.Elapsed.TotalSeconds;
            }

            // World has finished operations and concedes the thread to garbage collection
            WorldActive = false;
        }

19 View Source File : LandblockManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void UnloadLandblocks()
        {
            while (!destructionQueue.IsEmpty)
            {
                if (destructionQueue.TryTake(out Landblock landblock))
                {
                    landblock.Unload();

                    bool unloadFailed = false;

                    lock (landblockMutex)
                    {
                        // remove from list of managed landblocks
                        if (loadedLandblocks.Remove(landblock))
                        {
                            landblocks[landblock.Id.LandblockX, landblock.Id.LandblockY] = null;

                            // remove from landblock group
                            for (int i = landblockGroups.Count - 1; i >= 0 ; i--)
                            {
                                if (landblockGroups[i].Remove(landblock))
                                {
                                    if (landblockGroups[i].Count == 0)
                                        landblockGroups.RemoveAt(i);
                                    else if (ConfigManager.Config.Server.Threading.MulreplacedhreadedLandblockGroupPhysicsTicking || ConfigManager.Config.Server.Threading.MulreplacedhreadedLandblockGroupTicking) // Only try to split if multi-threading is enabled
                                    {
                                        swTrySplitEach.Restart();
                                        var splits = landblockGroups[i].TryThrottledSplit();
                                        swTrySplitEach.Stop();

                                        if (swTrySplitEach.Elapsed.TotalMilliseconds > 3)
                                            log.Warn($"[LANDBLOCK GROUP] TrySplit for {landblockGroups[i]} took: {swTrySplitEach.Elapsed.TotalMilliseconds:N2} ms");
                                        else if (swTrySplitEach.Elapsed.TotalMilliseconds > 1)
                                            log.Debug($"[LANDBLOCK GROUP] TrySplit for {landblockGroups[i]} took: {swTrySplitEach.Elapsed.TotalMilliseconds:N2} ms");

                                        if (splits != null)
                                        {
                                            if (splits.Count > 0)
                                            {
                                                log.Debug($"[LANDBLOCK GROUP] TrySplit resulted in {splits.Count} split(s) and took: {swTrySplitEach.Elapsed.TotalMilliseconds:N2} ms");
                                                log.Debug($"[LANDBLOCK GROUP] split for old: {landblockGroups[i]}");
                                            }

                                            foreach (var split in splits)
                                            {
                                                landblockGroups.Add(split);
                                                log.Debug($"[LANDBLOCK GROUP] split and new: {split}");
                                            }
                                        }
                                    }

                                    break;
                                }
                            }

                            NotifyAdjacents(landblock);
                        }
                        else
                            unloadFailed = true;
                    }

                    if (unloadFailed)
                        log.Error($"LandblockManager: failed to unload {landblock.Id.Raw:X8}");
                }
            }
        }

19 View Source File : WorldObject_Tick.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public virtual bool UpdateObjectPhysics()
        {
            // TODO: Almost all of the CPU time is spent between this note and the first Try block. Mag-nus 2019-10-21
            // TODO: In the future we should look at improving the way UpdateObjectPhysics() is called from Landblock
            // TODO: We should exclude objects that never tick physics (Monsters)
            // TODO: Perhaps for objects that have a throttle (Creatures), we use a list and only iterate through the pending creatures

            if (PhysicsObj == null || !PhysicsObj.is_active())
                return false;

            bool isDying = false;
            bool cachedVelocityFix = false;

            if (this is Creature creature)
            {
                if (LastPhysicsUpdate + UpdateRate_Creature > PhysicsTimer.CurrentTime)
                    return false;

                LastPhysicsUpdate = PhysicsTimer.CurrentTime;

                // monsters have separate physics updates,
                // except during the first frame of spawning, idle emotes, and dying
                isDying = creature.IsDead;

                // determine if updates should be run for object
                var runUpdate = PhysicsObj.IsAnimating && (!creature.IsMonster || !creature.IsAwake) || isDying || PhysicsObj.InitialUpdates <= 1;

                if (!runUpdate)
                    return false;

                if (creature.IsMonster && !creature.IsAwake)
                    cachedVelocityFix = true;
            }
            else
            {
                // arrows / spell projectiles
                //var isMissile = Missile ?? false;
                if ((PhysicsObj.State & PhysicsState.Missile) != 0) // This is a bit more performant than the line above
                {
                    if (physicsCreationTime + ProjectileTimeout <= PhysicsTimer.CurrentTime)
                    {
                        // only for projectiles?
                        //Console.WriteLine("Timeout reached - destroying " + Name);
                        PhysicsObj.set_active(false);
                        Destroy();
                        return false;
                    }

                    // missiles always run an update
                }
                else
                {
                    // determine if updates should be run for object
                    var runUpdate = PhysicsObj.IsAnimating || PhysicsObj.InitialUpdates <= 1;

                    if (!runUpdate)
                        return false;
                }
            }

            try
            {
                stopwatch.Restart();

                // get position before
                var prevPos = PhysicsObj.Position.Frame.Origin;
                var cellBefore = PhysicsObj.CurCell != null ? PhysicsObj.CurCell.ID : 0;

                //Console.WriteLine($"{Name} - ticking physics");
                var updated = PhysicsObj.update_object();

                // get position after
                var newPos = PhysicsObj.Position.Frame.Origin;

                // handle landblock / cell change
                var isMoved = (prevPos != newPos);
                var curCell = PhysicsObj.CurCell;

                if (PhysicsObj.CurCell == null)
                {
                    //Console.WriteLine("CurCell is null");
                    PhysicsObj.set_active(false);
                    Destroy();
                    return false;
                }

                var landblockUpdate = (cellBefore >> 16) != (curCell.ID >> 16);

                if (isMoved || isDying)
                {
                    if (curCell.ID != cellBefore)
                        Location.LandblockId = new LandblockId(curCell.ID);

                    // skip ObjCellID check when updating from physics
                    // TODO: update to newer version of ACE.Enreplacedy.Position
                    Location.PositionX = newPos.X;
                    Location.PositionY = newPos.Y;
                    Location.PositionZ = newPos.Z;

                    Location.Rotation = PhysicsObj.Position.Frame.Orientation;

                    //if (landblockUpdate)
                    //WorldManager.UpdateLandblock.Add(this);
                }

                /*if (PhysicsObj.IsGrounded)
                    SendUpdatePosition();*/

                //var dist = Vector3.Distance(ProjectileTarget.Location.Pos, newPos);
                //Console.WriteLine("Dist: " + dist);
                //Console.WriteLine("Velocity: " + PhysicsObj.Velocity);

                if (this is SpellProjectile spellProjectile)
                {
                    if (spellProjectile.Velocity == Vector3.Zero && spellProjectile.DebugVelocity < 30)
                    {
                        // todo: ensure this doesn't produce any false positives, then add mitigation code until fully debugged
                        spellProjectile.DebugVelocity++;

                        if (spellProjectile.DebugVelocity == 30)
                            log.Error($"Spell projectile w/ zero velocity detected @ {spellProjectile.Location.ToLOCString()}, launched by {spellProjectile.ProjectileSource?.Name} ({spellProjectile.ProjectileSource?.Guid}), spell ID {spellProjectile.Spell?.Id} - {spellProjectile.Spell?.Name}");
                    }

                    if (spellProjectile.SpellType == ProjectileSpellType.Ring)
                    {
                        var dist = spellProjectile.SpawnPos.DistanceTo(Location);
                        var maxRange = spellProjectile.Spell.BaseRangeConstant;
                        //Console.WriteLine("Max range: " + maxRange);
                        if (dist > maxRange)
                        {
                            PhysicsObj.set_active(false);
                            spellProjectile.ProjectileImpact();
                            return false;
                        }
                    }
                }

                if (cachedVelocityFix)
                    PhysicsObj.CachedVelocity = Vector3.Zero;

                return landblockUpdate;
            }
            finally
            {
                var elapsedSeconds = stopwatch.Elapsed.TotalSeconds;
                ServerPerformanceMonitor.AddToreplacedulativeEvent(ServerPerformanceMonitor.replacedulativeEventHistoryType.WorldObject_Tick_UpdateObjectPhysics, elapsedSeconds);
                if (elapsedSeconds >= 0.100) // Yea, that ain't good....
                {
                    slowUpdateObjectPhysicreplaced++;
                    log.Warn($"[PERFORMANCE][PHYSICS] {Guid}:{Name} took {(elapsedSeconds * 1000):N1} ms to process UpdateObjectPhysics() at loc: {Location}");

                    // Destroy laggy projectiles
                    if (slowUpdateObjectPhysicreplaced >= 5 && this is SpellProjectile spellProjectile)
                    {
                        PhysicsObj.set_active(false);
                        spellProjectile.ProjectileImpact();
                    }
                }
                else if (elapsedSeconds >= 0.010)
                {
                    slowUpdateObjectPhysicreplaced++;

                    // Destroy laggy projectiles
                    if (slowUpdateObjectPhysicreplaced >= 5 && this is SpellProjectile spellProjectile)
                    {
                        PhysicsObj.set_active(false);
                        spellProjectile.ProjectileImpact();

                        log.Warn($"[PERFORMANCE][PHYSICS] {Guid}:{Name} took {(elapsedSeconds * 1000):N1} ms to process UpdateObjectPhysics() at loc: {Location}. SpellProjectile destroyed.");
                    }
                    else
                        log.Debug($"[PERFORMANCE][PHYSICS] {Guid}:{Name} took {(elapsedSeconds * 1000):N1} ms to process UpdateObjectPhysics() at loc: {Location}");
                }
            }
        }

19 View Source File : FileContainerServer.cs
License : MIT License
Project Creator : actions

private async Task<DownloadResult> DownloadAsync(RunnerActionPluginExecutionContext context, int downloaderId, CancellationToken token)
        {
            List<DownloadInfo> failedFiles = new List<DownloadInfo>();
            Stopwatch downloadTimer = new Stopwatch();
            while (_fileDownloadQueue.TryDequeue(out DownloadInfo fileToDownload))
            {
                token.ThrowIfCancellationRequested();
                try
                {
                    int retryCount = 0;
                    bool downloadFailed = false;
                    while (true)
                    {
                        try
                        {
                            context.Debug($"Start downloading file: '{fileToDownload.ItemPath}' (Downloader {downloaderId})");
                            downloadTimer.Restart();
                            using (FileStream fs = new FileStream(fileToDownload.LocalPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: _defaultFileStreamBufferSize, useAsync: true))
                            using (var downloadStream = await _fileContainerHttpClient.DownloadFileAsync(_containerId, fileToDownload.ItemPath, token, _projectId))
                            {
                                await downloadStream.CopyToAsync(fs, _defaultCopyBufferSize, token);
                                await fs.FlushAsync(token);
                                downloadTimer.Stop();
                                context.Debug($"File: '{fileToDownload.LocalPath}' took {downloadTimer.ElapsedMilliseconds} milliseconds to finish download (Downloader {downloaderId})");
                                break;
                            }
                        }
                        catch (OperationCanceledException) when (token.IsCancellationRequested)
                        {
                            context.Debug($"Download has been cancelled while downloading {fileToDownload.ItemPath}. (Downloader {downloaderId})");
                            throw;
                        }
                        catch (Exception ex)
                        {
                            retryCount++;
                            context.Warning($"Fail to download '{fileToDownload.ItemPath}', error: {ex.Message} (Downloader {downloaderId})");
                            context.Debug(ex.ToString());
                        }

                        if (retryCount < 3)
                        {
                            var backOff = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30));
                            context.Warning($"Back off {backOff.TotalSeconds} seconds before retry. (Downloader {downloaderId})");
                            await Task.Delay(backOff);
                        }
                        else
                        {
                            // upload still failed after 3 tries.
                            downloadFailed = true;
                            break;
                        }
                    }

                    if (downloadFailed)
                    {
                        // tracking file that failed to download.
                        failedFiles.Add(fileToDownload);
                    }

                    Interlocked.Increment(ref _downloadFilesProcessed);
                }
                catch (Exception ex)
                {
                    // We should never
                    context.Error($"Error '{ex.Message}' when downloading file '{fileToDownload}'. (Downloader {downloaderId})");
                    throw ex;
                }
            }

            return new DownloadResult(failedFiles);
        }

19 View Source File : MessageListener.cs
License : MIT License
Project Creator : actions

public async Task<TaskAgentMessage> GetNextMessageAsync(CancellationToken token)
        {
            Trace.Entering();
            ArgUtil.NotNull(_session, nameof(_session));
            ArgUtil.NotNull(_settings, nameof(_settings));
            bool encounteringError = false;
            int continuousError = 0;
            string errorMessage = string.Empty;
            Stopwatch heartbeat = new Stopwatch();
            heartbeat.Restart();
            while (true)
            {
                token.ThrowIfCancellationRequested();
                TaskAgentMessage message = null;
                try
                {
                    message = await _runnerServer.GetAgentMessageAsync(_settings.PoolId,
                                                                _session.SessionId,
                                                                _lastMessageId,
                                                                token);

                    // Decrypt the message body if the session is using encryption
                    message = DecryptMessage(message);

                    if (message != null)
                    {
                        _lastMessageId = message.MessageId;
                    }

                    if (encounteringError) //print the message once only if there was an error
                    {
                        _term.WriteLine($"{DateTime.UtcNow:u}: Runner reconnected.");
                        encounteringError = false;
                        continuousError = 0;
                    }
                }
                catch (OperationCanceledException) when (token.IsCancellationRequested)
                {
                    Trace.Info("Get next message has been cancelled.");
                    throw;
                }
                catch (TaskAgentAccessTokenExpiredException)
                {
                    Trace.Info("Runner OAuth token has been revoked. Unable to pull message.");
                    throw;
                }
                catch (Exception ex)
                {
                    Trace.Error("Catch exception during get next message.");
                    Trace.Error(ex);

                    // don't retry if SkipSessionRecover = true, DT service will delete agent session to stop agent from taking more jobs.
                    if (ex is TaskAgentSessionExpiredException && !_settings.SkipSessionRecover && await CreateSessionAsync(token))
                    {
                        Trace.Info($"{nameof(TaskAgentSessionExpiredException)} received, recovered by recreate session.");
                    }
                    else if (!IsGetNextMessageExceptionRetriable(ex))
                    {
                        throw;
                    }
                    else
                    {
                        continuousError++;
                        //retry after a random backoff to avoid service throttling
                        //in case of there is a service error happened and all agents get kicked off of the long poll and all agent try to reconnect back at the same time.
                        if (continuousError <= 5)
                        {
                            // random backoff [15, 30]
                            _getNextMessageRetryInterval = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), _getNextMessageRetryInterval);
                        }
                        else
                        {
                            // more aggressive backoff [30, 60]
                            _getNextMessageRetryInterval = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(60), _getNextMessageRetryInterval);
                        }

                        if (!encounteringError)
                        {
                            //print error only on the first consecutive error
                            _term.WriteError($"{DateTime.UtcNow:u}: Runner connect error: {ex.Message}. Retrying until reconnected.");
                            encounteringError = true;
                        }

                        // re-create VssConnection before next retry
                        await _runnerServer.RefreshConnectionAsync(RunnerConnectionType.MessageQueue, TimeSpan.FromSeconds(60));

                        Trace.Info("Sleeping for {0} seconds before retrying.", _getNextMessageRetryInterval.TotalSeconds);
                        await HostContext.Delay(_getNextMessageRetryInterval, token);
                    }
                }

                if (message == null)
                {
                    if (heartbeat.Elapsed > TimeSpan.FromMinutes(30))
                    {
                        Trace.Info($"No message retrieved from session '{_session.SessionId}' within last 30 minutes.");
                        heartbeat.Restart();
                    }
                    else
                    {
                        Trace.Verbose($"No message retrieved from session '{_session.SessionId}'.");
                    }

                    continue;
                }

                Trace.Info($"Message '{message.MessageId}' received from session '{_session.SessionId}'.");
                return message;
            }
        }

19 View Source File : FileContainerServer.cs
License : MIT License
Project Creator : actions

private async Task<UploadResult> UploadAsync(RunnerActionPluginExecutionContext context, int uploaderId, CancellationToken token)
        {
            List<string> failedFiles = new List<string>();
            long uploadedSize = 0;
            string fileToUpload;
            Stopwatch uploadTimer = new Stopwatch();
            while (_fileUploadQueue.TryDequeue(out fileToUpload))
            {
                token.ThrowIfCancellationRequested();
                try
                {
                    using (FileStream fs = File.Open(fileToUpload, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        string itemPath = (_containerPath.TrimEnd('/') + "/" + fileToUpload.Remove(0, _sourceParentDirectory.Length + 1)).Replace('\\', '/');
                        bool failAndExit = false;
                        try
                        {
                            uploadTimer.Restart();
                            using (HttpResponseMessage response = await _fileContainerHttpClient.UploadFileAsync(_containerId, itemPath, fs, _projectId, cancellationToken: token, chunkSize: 4 * 1024 * 1024))
                            {
                                if (response == null || response.StatusCode != HttpStatusCode.Created)
                                {
                                    context.Output($"Unable to copy file to server StatusCode={response?.StatusCode}: {response?.ReasonPhrase}. Source file path: {fileToUpload}. Target server path: {itemPath}");

                                    if (response?.StatusCode == HttpStatusCode.Conflict)
                                    {
                                        // fail upload task but continue with any other files
                                        context.Error($"Error '{fileToUpload}' has already been uploaded.");
                                    }
                                    else if (_fileContainerHttpClient.IsFastFailResponse(response))
                                    {
                                        // Fast fail: we received an http status code where we should abandon our efforts
                                        context.Output($"Cannot continue uploading files, so draining upload queue of {_fileUploadQueue.Count} items.");
                                        DrainUploadQueue(context);
                                        failedFiles.Clear();
                                        failAndExit = true;
                                        throw new UploadFailedException($"Critical failure uploading '{fileToUpload}'");
                                    }
                                    else
                                    {
                                        context.Debug($"Adding '{fileToUpload}' to retry list.");
                                        failedFiles.Add(fileToUpload);
                                    }
                                    throw new UploadFailedException($"Http failure response '{response?.StatusCode}': '{response?.ReasonPhrase}' while uploading '{fileToUpload}'");
                                }

                                uploadTimer.Stop();
                                context.Debug($"File: '{fileToUpload}' took {uploadTimer.ElapsedMilliseconds} milliseconds to finish upload");
                                uploadedSize += fs.Length;
                                OutputLogForFile(context, fileToUpload, $"Detail upload trace for file: {itemPath}", context.Debug);
                            }
                        }
                        catch (OperationCanceledException) when (token.IsCancellationRequested)
                        {
                            context.Output($"File upload has been cancelled during upload file: '{fileToUpload}'.");
                            throw;
                        }
                        catch (Exception ex)
                        {
                            context.Output($"Fail to upload '{fileToUpload}' due to '{ex.Message}'.");
                            context.Output(ex.ToString());

                            OutputLogForFile(context, fileToUpload, $"Detail upload trace for file that fail to upload: {itemPath}", context.Output);

                            if (failAndExit)
                            {
                                context.Debug("Exiting upload.");
                                throw;
                            }
                        }
                    }

                    Interlocked.Increment(ref _uploadFilesProcessed);
                }
                catch (Exception ex)
                {
                    context.Output($"File error '{ex.Message}' when uploading file '{fileToUpload}'.");
                    throw ex;
                }
            }

            return new UploadResult(failedFiles, uploadedSize);
        }

19 View Source File : FileContainerHttpClient.cs
License : MIT License
Project Creator : actions

[EditorBrowsable(EditorBrowsableState.Never)]
        public async Task<HttpResponseMessage> UploadFileAsync(
            Int64 containerId,
            String itemPath,
            Stream fileStream,
            byte[] contentId,
            Int64 fileLength,
            Boolean isGzipped,
            Guid scopeIdentifier,
            CancellationToken cancellationToken = default(CancellationToken),
            int chunkSize = c_defaultChunkSize,
            int chunkRetryTimes = c_defaultChunkRetryTimes,
            bool uploadFirstChunk = false,
            Object userState = null)
        {
            if (containerId < 1)
            {
                throw new ArgumentException(WebApiResources.ContainerIdMustBeGreaterThanZero(), "containerId");
            }

            if (chunkSize > c_maxChunkSize)
            {
                chunkSize = c_maxChunkSize;
            }

            // if a contentId is specified but the chunk size is not a 2mb multiple error
            if (contentId != null && (chunkSize % c_ContentChunkMultiple) != 0)
            {
                throw new ArgumentException(FileContainerResources.ChunksizeWrongWithContentId(c_ContentChunkMultiple), "chunkSize");
            }

            ArgumentUtility.CheckForNull(fileStream, "fileStream");

            ApiResourceVersion gzipSupportedVersion = new ApiResourceVersion(new Version(1, 0), 2);
            ApiResourceVersion requestVersion = await NegotiateRequestVersionAsync(FileContainerResourceIds.FileContainer, s_currentApiVersion, userState, cancellationToken).ConfigureAwait(false);

            if (isGzipped
                && (requestVersion.ApiVersion < gzipSupportedVersion.ApiVersion
                    || (requestVersion.ApiVersion == gzipSupportedVersion.ApiVersion && requestVersion.ResourceVersion < gzipSupportedVersion.ResourceVersion)))
            {
                throw new ArgumentException(FileContainerResources.GzipNotSupportedOnServer(), "isGzipped");
            }

            if (isGzipped && fileStream.Length >= fileLength)
            {
                throw new ArgumentException(FileContainerResources.BadCompression(), "fileLength");
            }

            HttpRequestMessage requestMessage = null;
            List<KeyValuePair<String, String>> query = AppendItemQueryString(itemPath, scopeIdentifier);

            if (fileStream.Length == 0)
            {
                // zero byte upload
                FileUploadTrace(itemPath, $"Upload zero byte file '{itemPath}'.");
                requestMessage = await CreateRequestMessageAsync(HttpMethod.Put, FileContainerResourceIds.FileContainer, routeValues: new { containerId = containerId }, version: s_currentApiVersion, queryParameters: query, userState: userState, cancellationToken: cancellationToken).ConfigureAwait(false);
                return await SendAsync(requestMessage, userState, cancellationToken).ConfigureAwait(false);
            }

            bool multiChunk = false;
            int totalChunks = 1;
            if (fileStream.Length > chunkSize)
            {
                totalChunks = (int)Math.Ceiling(fileStream.Length / (double)chunkSize);
                FileUploadTrace(itemPath, $"Begin chunking upload file '{itemPath}', chunk size '{chunkSize} Bytes', total chunks '{totalChunks}'.");
                multiChunk = true;
            }
            else
            {
                FileUploadTrace(itemPath, $"File '{itemPath}' will be uploaded in one chunk.");
                chunkSize = (int)fileStream.Length;
            }

            StreamParser streamParser = new StreamParser(fileStream, chunkSize);
            SubStream currentStream = streamParser.GetNextStream();
            HttpResponseMessage response = null;

            Byte[] dataToSend = new Byte[chunkSize];
            int currentChunk = 0;
            Stopwatch uploadTimer = new Stopwatch();
            while (currentStream.Length > 0 && !cancellationToken.IsCancellationRequested)
            {
                currentChunk++;

                for (int attempt = 1; attempt <= chunkRetryTimes && !cancellationToken.IsCancellationRequested; attempt++)
                {
                    if (attempt > 1)
                    {
                        TimeSpan backoff = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10));
                        FileUploadTrace(itemPath, $"Backoff {backoff.TotalSeconds} seconds before attempt '{attempt}' chunk '{currentChunk}' of file '{itemPath}'.");
                        await Task.Delay(backoff, cancellationToken).ConfigureAwait(false);
                        currentStream.Seek(0, SeekOrigin.Begin);
                    }

                    FileUploadTrace(itemPath, $"Attempt '{attempt}' for uploading chunk '{currentChunk}' of file '{itemPath}'.");

                    // inorder for the upload to be retryable, we need the content to be re-readable
                    // to ensure this we copy the chunk into a byte array and send that
                    // chunk size ensures we can convert the length to an int
                    int bytesToCopy = (int)currentStream.Length;
                    using (MemoryStream ms = new MemoryStream(dataToSend))
                    {
                        await currentStream.CopyToAsync(ms, bytesToCopy, cancellationToken).ConfigureAwait(false);
                    }

                    // set the content and the Content-Range header
                    HttpContent byteArrayContent = new ByteArrayContent(dataToSend, 0, bytesToCopy);
                    byteArrayContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                    byteArrayContent.Headers.ContentLength = currentStream.Length;
                    byteArrayContent.Headers.ContentRange = new System.Net.Http.Headers.ContentRangeHeaderValue(currentStream.StartingPostionOnOuterStream,
                                                                                                             currentStream.EndingPostionOnOuterStream,
                                                                                                             streamParser.Length);
                    FileUploadTrace(itemPath, $"Generate new HttpRequest for uploading file '{itemPath}', chunk '{currentChunk}' of '{totalChunks}'.");

                    try
                    {
                        if (requestMessage != null)
                        {
                            requestMessage.Dispose();
                            requestMessage = null;
                        }

                        requestMessage = await CreateRequestMessageAsync(
                            HttpMethod.Put,
                            FileContainerResourceIds.FileContainer,
                            routeValues: new { containerId = containerId },
                            version: s_currentApiVersion,
                            content: byteArrayContent,
                            queryParameters: query,
                            userState: userState,
                            cancellationToken: cancellationToken).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
                    {
                        // stop re-try on cancellation.
                        throw;
                    }
                    catch (Exception ex) when (attempt < chunkRetryTimes) // not the last attempt
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' fail to create HttpRequest. Error: {ex.ToString()}.");
                        continue;
                    }

                    if (isGzipped)
                    {
                        //add gzip header info
                        byteArrayContent.Headers.ContentEncoding.Add("gzip");
                        byteArrayContent.Headers.Add("x-tfs-filelength", fileLength.ToString(System.Globalization.CultureInfo.InvariantCulture));
                    }

                    if (contentId != null)
                    {
                        byteArrayContent.Headers.Add("x-vso-contentId", Convert.ToBase64String(contentId)); // Base64FormattingOptions.None is default when not supplied
                    }

                    FileUploadTrace(itemPath, $"Start uploading file '{itemPath}' to server, chunk '{currentChunk}'.");
                    uploadTimer.Restart();

                    try
                    {
                        if (response != null)
                        {
                            response.Dispose();
                            response = null;
                        }

                        response = await SendAsync(requestMessage, userState, cancellationToken).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
                    {
                        // stop re-try on cancellation.
                        throw;
                    }
                    catch (Exception ex) when (attempt < chunkRetryTimes) // not the last attempt
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' fail to send request to server. Error: {ex.ToString()}.");
                        continue;
                    }

                    uploadTimer.Stop();
                    FileUploadTrace(itemPath, $"Finished upload chunk '{currentChunk}' of file '{itemPath}', elapsed {uploadTimer.ElapsedMilliseconds} (ms), response code '{response.StatusCode}'.");

                    if (multiChunk)
                    {
                        FileUploadProgress(itemPath, currentChunk, (int)Math.Ceiling(fileStream.Length / (double)chunkSize));
                    }

                    if (response.IsSuccessStatusCode)
                    {
                        break;
                    }
                    else if (IsFastFailResponse(response))
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' received non-success status code {response.StatusCode} for sending request and cannot continue.");
                        break;
                    }
                    else
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' received non-success status code {response.StatusCode} for sending request.");
                        continue;
                    }
                }

                // if we don't have success then bail and return the failed response
                if (!response.IsSuccessStatusCode)
                {
                    break;
                }

                if (contentId != null && response.StatusCode == HttpStatusCode.Created)
                {
                    // no need to keep uploading since the server said it has all the content
                    FileUploadTrace(itemPath, $"Stop chunking upload the rest of the file '{itemPath}', since server already has all the content.");
                    break;
                }

                currentStream = streamParser.GetNextStream();
                if (uploadFirstChunk)
                {
                    break;
                }
            }

            cancellationToken.ThrowIfCancellationRequested();

            return response;
        }

19 View Source File : EventHost4.cs
License : MIT License
Project Creator : ad313

private async Task CreateRpcService2()
        {
            _eventBusProvider.RpcServer<int>("aaa", async data =>
            {
                await Task.CompletedTask;

                //throw new Exception($"error in {data}");

                //await Task.Delay(5000);
                return new RpcResult($"aaa from {data}");
            });
            
            await Task.Delay(2000);

            Console.WriteLine($"begin---");

            var watch = Stopwatch.StartNew();
            watch.Start();

            var w2 = Stopwatch.StartNew();
            for (int i = 0; i < 1; i++)
            {
                w2.Restart();
                var result = await _eventBusProvider.RpcClientAsync<string>("aaa", new object[] { i });
                Console.WriteLine($"{result.Data}--{i} {w2.ElapsedMilliseconds}");
            }
            w2.Stop();


            //var tasks1 = Enumerable.Range(0, 10).Select(i => Task.Run(async () =>
            //{
            //    var result = await _eventBusProvider.RpcClientAsync("aaa", i);
            //    Console.WriteLine($"{result.Data}--{i}");
            //})).ToList();


            //watch.Start();

            //Task.WaitAll(tasks1.ToArray());
            watch.Stop();

            Console.WriteLine($"end {watch.ElapsedMilliseconds}");
        }

19 View Source File : EventHost4.cs
License : MIT License
Project Creator : ad313

private async Task CreateRpcService3()
        {
            _eventBusProvider.RpcServer<int>("aaa", async data =>
            {
                await Task.CompletedTask;

                //throw new Exception($"error in {data}");

                //await Task.Delay(5000);
                return new RpcResult($"aaa from {data}");
            });

            _eventBusProvider.RpcServer<int>("aaa", async data =>
            {
                await Task.CompletedTask;

                //throw new Exception($"error in {data}");

                //await Task.Delay(5000);
                return new RpcResult($"aaa from {data}");
            });



            _eventBusProvider.RpcServer<int>("bbb", async data =>
            {
                await Task.CompletedTask;

                //throw new Exception($"error in {data}");

                //await Task.Delay(5000);
                return new RpcResult($"bbb from {data}");
            });


            _eventBusProvider.RpcServer<int>("ccc", async data =>
            {
                await Task.CompletedTask;

                //throw new Exception($"error in {data}");

                //await Task.Delay(5000);
                return new RpcResult($"ccc from {data}");
            });

            await Task.Delay(2000);

            Console.WriteLine($"begin---");

            var watch = Stopwatch.StartNew();
            //watch.Start();

            var w2 = Stopwatch.StartNew();
            for (int i = 0; i < 10; i++)
            {
                w2.Restart();
                var result = await _eventBusProvider.RpcClientAsync<string>("aaa", new object[] { i });
                Console.WriteLine($"{result.Data}--{i} {w2.ElapsedMilliseconds}");
            }
            w2.Stop();

            for (int i = 100; i < 110; i++)
            {
                w2.Restart();
                var result = await _eventBusProvider.RpcClientAsync<string>("bbb", new object[] { i });
                Console.WriteLine($"{result.Data}--{i} {w2.ElapsedMilliseconds}");
            }

            for (int i = 1000; i < 1010; i++)
            {
                w2.Restart();
                var result = await _eventBusProvider.RpcClientAsync<string>("ccc", new object[] { i });
                Console.WriteLine($"{result.Data}--{i} {w2.ElapsedMilliseconds}");
            }


            //var tasks1 = Enumerable.Range(0, 10).Select(i => Task.Run(async () =>
            //{
            //    var result = await _eventBusProvider.RpcClientAsync("aaa", i);
            //    Console.WriteLine($"{result.Data}--{i}");
            //})).ToList();

            //var tasks2 = Enumerable.Range(100, 10).Select(i => Task.Run(async () =>
            //{
            //    var result = await _eventBusProvider.RpcClientAsync("bbb", i);
            //    Console.WriteLine($"{result.Data}--{i}");
            //})).ToList();

            //var tasks3 = Enumerable.Range(1000, 10).Select(i => Task.Run(async () =>
            //{
            //    var result = await _eventBusProvider.RpcClientAsync("ccc", i);
            //    Console.WriteLine($"{result.Data}--{i}");
            //})).ToList();

            //tasks1.AddRange(tasks2);
            //tasks1.AddRange(tasks3);

            //watch.Start();

            //Task.WaitAll(tasks1.ToArray());
            //watch.Stop();

            Console.WriteLine($"end {watch.ElapsedMilliseconds}");
        }

19 View Source File : AssetManager.cs
License : MIT License
Project Creator : Adsito

public static IEnumerator SetBundleReferences((int parent, int bundle) ID)
		{
			var sw = new System.Diagnostics.Stopwatch();
			sw.Start();

			foreach (var replacedet in BundleCache.Values)
			{
				foreach (var filename in replacedet.GetAllreplacedetNames())
				{
					BundleLookup.Add(filename, replacedet);
					if (sw.Elapsed.TotalMilliseconds >= 0.5f)
					{
						yield return null;
						sw.Restart();    
					}
				}
				foreach (var filename in replacedet.GetAllScenePaths())
				{
					BundleLookup.Add(filename, replacedet);
					if (sw.Elapsed.TotalMilliseconds >= 0.5f)
					{
						yield return null;
						sw.Restart();
					}
				}
			}

			Progress.Report(ID.bundle, 0.99f, "Loaded " + BundleCache.Count + " bundles.");
			Progress.Finish(ID.bundle, Progress.Status.Succeeded);

			Manifest = Getreplacedet<GameManifest>(ManifestPath);
			if (Manifest == null)
			{
				Debug.LogError("Couldn't load GameManifest.");
				Dispose();
				Progress.Finish(ID.parent, Progress.Status.Failed);
				yield break;
			}

			var setLookups = Task.Run(() =>
			{
				for (uint i = 0; i < Manifest.pooledStrings.Length; ++i)
				{
					IDLookup.Add(Manifest.pooledStrings[i].hash, Manifest.pooledStrings[i].str);
					PathLookup.Add(Manifest.pooledStrings[i].str, Manifest.pooledStrings[i].hash);
					if (ToID(Manifest.pooledStrings[i].str) != 0)
						replacedetPaths.Add(Manifest.pooledStrings[i].str);
				}
				replacedetDump();
			});
			while (!setLookups.IsCompleted)
            {
				if (sw.Elapsed.TotalMilliseconds >= 0.1f)
                {
					yield return null;
					sw.Restart();
				}
			}
		}

19 View Source File : PrefabManager.cs
License : MIT License
Project Creator : Adsito

public static IEnumerator SpawnPrefabs(PrefabData[] prefabs, int progressID)
        {
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            for (int i = 0; i < prefabs.Length; i++)
            {
                if (sw.Elapsed.TotalSeconds > 4f)
                {
                    yield return null;
                    Progress.Report(progressID, (float)i / prefabs.Length, "Spawning Prefabs: " + i + " / " + prefabs.Length);
                    sw.Restart();
                }
                Spawn(Load(prefabs[i].id), prefabs[i], GetParent(prefabs[i].category));
            }

            Progress.Report(progressID, 0.99f, "Spawned " + prefabs.Length + " prefabs.");
            Progress.Finish(progressID, Progress.Status.Succeeded);
        }

19 View Source File : PrefabManager.cs
License : MIT License
Project Creator : Adsito

public static IEnumerator DeletePrefabs(PrefabDataHolder[] prefabs, int progressID = 0)
        {
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            if (progressID == 0)
                progressID = Progress.Start("Delete Prefabs", null, Progress.Options.Sticky);

            for (int i = 0; i < prefabs.Length; i++)
            {
                if (sw.Elapsed.TotalSeconds > 0.25f)
                {
                    yield return null;
                    Progress.Report(progressID, (float)i / prefabs.Length, "Deleting Prefabs: " + i + " / " + prefabs.Length);
                    sw.Restart();
                }
                GameObject.DestroyImmediate(prefabs[i].gameObject);
            }

            Progress.Report(progressID, 0.99f, "Deleted " + prefabs.Length + " prefabs.");
            Progress.Finish(progressID, Progress.Status.Succeeded);
        }

19 View Source File : PrefabManager.cs
License : MIT License
Project Creator : Adsito

public static IEnumerator ReplaceWithLoaded(PrefabDataHolder[] prefabs, int progressID)
        {
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            for (int i = 0; i < prefabs.Length; i++)
            {
                if (sw.Elapsed.TotalSeconds > 4f)
                {
                    yield return null;
                    Progress.Report(progressID, (float)i / prefabs.Length, "Replacing Prefabs: " + i + " / " + prefabs.Length);
                    sw.Restart();
                }
                prefabs[i].UpdatePrefabData();
                Spawn(Load(prefabs[i].prefabData.id), prefabs[i].prefabData, GetParent(prefabs[i].prefabData.category));
                GameObject.DestroyImmediate(prefabs[i].gameObject);
            }

            Progress.Report(progressID, 0.99f, "Replaced " + prefabs.Length + " prefabs.");
            Progress.Finish(progressID, Progress.Status.Succeeded);
            IsChangingPrefabs = false;
        }

19 View Source File : PrefabManager.cs
License : MIT License
Project Creator : Adsito

public static IEnumerator ReplaceWithDefault(PrefabDataHolder[] prefabs, int progressID)
        {
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            for (int i = 0; i < prefabs.Length; i++)
            {
                if (sw.Elapsed.TotalSeconds > 0.05f)
                {
                    yield return null;
                    Progress.Report(progressID, (float)i / prefabs.Length, "Replacing Prefabs: " + i + " / " + prefabs.Length);
                    sw.Restart();
                }
                prefabs[i].UpdatePrefabData();
                Spawn(DefaultPrefab, prefabs[i].prefabData, GetParent(prefabs[i].prefabData.category));
                GameObject.DestroyImmediate(prefabs[i].gameObject);
            }

            Progress.Report(progressID, 0.99f, "Replaced " + prefabs.Length + " prefabs.");
            Progress.Finish(progressID, Progress.Status.Succeeded);
            IsChangingPrefabs = false;
        }

19 View Source File : PrefabManager.cs
License : MIT License
Project Creator : Adsito

public static IEnumerator RenamePrefabIDs(PrefabDataHolder[] prefabs, uint id, bool replace)
        {
            ProgressManager.RemoveProgressBars("Rename Prefab IDs");
            int progressId = Progress.Start("Rename Prefab IDs", null, Progress.Options.Sticky);

            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            for (int i = 0; i < prefabs.Length; i++)
            {
                prefabs[i].prefabData.id = id;
                Callbacks.OnPrefabIDChanged(prefabs[i].gameObject);
                if (replace)
                {
                    prefabs[i].UpdatePrefabData();
                    Spawn(Load(prefabs[i].prefabData.id), prefabs[i].prefabData, GetParent(prefabs[i].prefabData.category));
                    GameObject.DestroyImmediate(prefabs[i].gameObject);
                }
                if (sw.Elapsed.TotalSeconds > 0.2f)
                {
                    yield return null;
                    Progress.Report(progressId, (float)i / prefabs.Length, "Renaming Prefab: " + i + " / " + prefabs.Length);
                    sw.Restart();
                }
            }

            Progress.Report(progressId, 0.99f, "Renamed: " + prefabs.Length + " prefabs.");
            Progress.Finish(progressId);
        }

19 View Source File : MapManager.cs
License : MIT License
Project Creator : Adsito

public static IEnumerator Load(MapInfo mapInfo, string path = "")
        {
            ProgressManager.RemoveProgressBars("Load:");

            int progressID = Progress.Start("Load: " + path.Split('/').Last(), "Preparing Map", Progress.Options.Sticky);
            int delPrefab = Progress.Start("Prefabs", null, Progress.Options.Sticky, progressID);
            int spwPrefab = Progress.Start("Prefabs", null, Progress.Options.Sticky, progressID);
            int delPath = Progress.Start("Paths", null, Progress.Options.Sticky, progressID);
            int spwPath = Progress.Start("Paths", null, Progress.Options.Sticky, progressID);
            int terrainID = Progress.Start("Terrain", null, Progress.Options.Sticky, progressID);

            PrefabManager.DeletePrefabs(PrefabManager.CurrentMapPrefabs, delPrefab);
            PathManager.DeletePaths(PathManager.CurrentMapPaths, delPath);
            CentreSceneObjects(mapInfo);
            TerrainManager.Load(mapInfo, terrainID);
            PrefabManager.SpawnPrefabs(mapInfo.prefabData, spwPrefab);
            PathManager.SpawnPaths(mapInfo.pathData, spwPath);

            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            while (Progress.GetProgressById(terrainID).progress < 0.99f || Progress.GetProgressById(spwPrefab).running || Progress.GetProgressById(spwPath).running)
            {
                if (sw.Elapsed.TotalMilliseconds > 0.05f)
                {
                    sw.Restart();
                    yield return null;
                }
            }

            Progress.Report(progressID, 0.99f, "Loaded");
            Progress.Finish(terrainID, Progress.Status.Succeeded);
            Progress.Finish(progressID, Progress.Status.Succeeded);

            Callbacks.OnMapLoaded(path);
        }

19 View Source File : PathManager.cs
License : MIT License
Project Creator : Adsito

public static IEnumerator SpawnPaths(PathData[] paths, int progressID)
        {
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            for (int i = 0; i < paths.Length; i++)
            {
                if (sw.Elapsed.TotalSeconds > 0.1f)
                {
                    yield return null;
                    Progress.Report(progressID, (float)i / paths.Length, "Spawning Paths: " + i + " / " + paths.Length);
                    sw.Restart();
                }
                SpawnPath(paths[i]);
            }
            Progress.Report(progressID, 0.99f, "Spawned " + paths.Length + " paths.");
            Progress.Finish(progressID, Progress.Status.Succeeded);
        }

19 View Source File : PathManager.cs
License : MIT License
Project Creator : Adsito

public static IEnumerator DeletePaths(PathDataHolder[] paths, int progressID = 0)
        {
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            if (progressID == 0)
                progressID = Progress.Start("Delete Paths", null, Progress.Options.Sticky);

            for (int i = 0; i < paths.Length; i++)
            {
                if (sw.Elapsed.TotalSeconds > 0.1f)
                {
                    yield return null;
                    Progress.Report(progressID, (float)i / paths.Length, "Deleting Paths: " + i + " / " + paths.Length);
                    sw.Restart();
                }
                GameObject.DestroyImmediate(paths[i].gameObject);
            }
            Progress.Report(progressID, 0.99f, "Deleted " + paths.Length + " paths.");
            Progress.Finish(progressID, Progress.Status.Succeeded);
        }

19 View Source File : PrefabManager.cs
License : MIT License
Project Creator : Adsito

public static IEnumerator RenamePrefabCategories(PrefabDataHolder[] prefabs, string name)
        {
            ProgressManager.RemoveProgressBars("Rename Prefab Categories");
            int progressId = Progress.Start("Rename Prefab Categories", null, Progress.Options.Sticky);

            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            for (int i = 0; i < prefabs.Length; i++)
            {
                prefabs[i].prefabData.category = name;
                Callbacks.OnPrefabCategoryChanged(prefabs[i].gameObject);
                if (sw.Elapsed.TotalSeconds > 0.2f)
                {
                    yield return null;
                    Progress.Report(progressId, (float)i / prefabs.Length, "Renaming Prefab: " + i + " / " + prefabs.Length);
                    sw.Restart();
                }
            }

            Progress.Report(progressId, 0.99f, "Renamed: " + prefabs.Length + " prefabs.");
            Progress.Finish(progressId);
        }

19 View Source File : NetManager.cs
License : GNU General Public License v3.0
Project Creator : aglab2

public override bool CheckInvalidated()
        {
            bool invalidated = false;
            if (deadWatch.ElapsedMilliseconds > 30000)
            {
                if (deadPlayers.Count() != 0)
                {
                    invalidated = true;
                    mustReload = true;
                    foreach (var player in deadPlayers)
                    {
                        players.Remove(player);
                    }
                }
                deadPlayers = new List<string>(players);
                deadWatch.Restart();
            }

            {
                var elapsed = watch.ElapsedMilliseconds;
                if(elapsed > 30)
                {
                    invalidated = true;
                    watch.Restart();
                }
            }

            return invalidated;
        }

19 View Source File : RetryAction.cs
License : Apache License 2.0
Project Creator : agoda-com

public async Task<IReadOnlyList<RetryActionResult<TSource, TResult>>> ExecuteAsyncWithDiag<TResult>(
            RandomSourceAsyncFunc<TSource, TResult> taskFunc,
            ShouldRetryPredicate shouldRetry,
            OnError onError = null)
        {
            var stopwatch = new Stopwatch();
            var results = new List<RetryActionResult<TSource, TResult>>();
            for (var attemptCount = 1; ; attemptCount++)
            {
                var item = _chooseRandomly();
                try
                {
                    stopwatch.Restart();
                    var result = await taskFunc(item, attemptCount).ConfigureAwait(false);
                    _updateWeight(item, true);
                    results.Add(new RetryActionResult<TSource, TResult>(
                        item, result, stopwatch.Elapsed, null, attemptCount));
                    break;
                }
                catch (Exception e)
                {
                    results.Add(new RetryActionResult<TSource, TResult>(
                        item, default(TResult), stopwatch.Elapsed, e, attemptCount));
                    _updateWeight(item, false);
                    var isFailed = !shouldRetry(attemptCount, e);
                    if (isFailed)
                    {
                        break;
                    }
                }
            }
            return results;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : Alan-FGR

static void Measure<T>(string text, bool warmup, Func<T> func)
    {
        if (warmup)
        {
            Console.WriteLine($"Warming up... ");
            func.Invoke();
            return;
        }

        Console.Write($"Measuring... ");

        sw_.Restart();
        T r = func.Invoke();
        float elapsedMicroseconds = sw_.ElapsedMicroseconds();

        if (!results_.ContainsKey(text))
            results_[text] = new List<float>();
        results_[text].Add(elapsedMicroseconds);

        Console.WriteLine($"it took {elapsedMicroseconds.ToString("f0").PadLeft(5)} µs to {text}. Result: {r}");
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : Alan-FGR

private unsafe void Run()
    {
        Stopwatch clock = new Stopwatch();
        bool quit = false;
        while (!quit)
        {
            var frameTime = clock.Elapsed.TotalMilliseconds;
            clock.Restart();

            while (SDL_PollEvent(out SDL_Event sdlEvent) != 0)
            {
                if (sdlEvent.type == SDL_EventType.SDL_QUIT) quit = true;
                if (sdlEvent.type == SDL_EventType.SDL_WINDOWEVENT &&
                    sdlEvent.window.windowEvent == SDL_WindowEventID.SDL_WINDOWEVENT_SIZE_CHANGED)
                    UpdateWindowSize();
                if (HasMouseFocus)
                {
                    if (sdlEvent.type == SDL_EventType.SDL_MOUSEMOTION &&
                        (SDL_GetMouseState(IntPtr.Zero, IntPtr.Zero) & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0)
                    {
                        const float mSens = 0.5f;
                        cameraPosition.yaw   += sdlEvent.motion.xrel * -mSens;
                        cameraPosition.pitch += sdlEvent.motion.yrel * mSens;
                    }

                    if (sdlEvent.type == SDL_EventType.SDL_MOUSEWHEEL)
                    {
                        cameraPosition.dist *= 1 + sdlEvent.wheel.y * -0.1f;
                    }

                    byte* state = (byte*)SDL_GetKeyboardState(out var numkeys);

                    if (state[(int)SDL_GetScancodeFromKey(SDL_Keycode.SDLK_w)] != 0)
                        targetHeight += 1;
                    if (state[(int)SDL_GetScancodeFromKey(SDL_Keycode.SDLK_s)] != 0)
                        targetHeight -= 1;

                }
            }

            OnUpdate(frameTime);

            pxScene.simulate(1/60f);
            pxScene.fetchResults(true);

            SetupView();
            SubmitLines();

            Bgfx.DebugTextClear();
            Bgfx.DebugTextWrite(0, 0, DebugColor.Blue, DebugColor.LightGreen, 
                $"SharpPhysX DebugRenderer. FPS: {(int)(1000/frameTime+0.5f)}, frame time: {frameTime:##.00}ms");

            Bgfx.Frame();
        }

        ShutdownPhysX();
        ShutdownRenderer();
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : Alan-FGR

[MethodImpl(MethodImplOptions.AggressiveInlining)]
    static void Measure(string previousMeasurement = null)
    {
        sw.Stop();
        if (previousMeasurement != null) Console.WriteLine($"{sw.Elapsed.TotalMilliseconds:00.00} ms {previousMeasurement}");
        sw.Restart();
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : Alan-FGR

private static void StressMiniDict()
    {
        const int V = 20;
        var keys = new Flags[V];
        for (int i = 0; i < V; i++)
            keys[i] = new Flags(i);
        var mDict = new MiniDict<Flags, int>(keys);

        var nDict = new Dictionary<Flags, int>(V);


        for (int i = 0; i < V; i++)
        {
            mDict[new Flags(i)] = i;
        }

        for (int i = 0; i < V; i++)
        {
            nDict[new Flags(i)] = i;
        }

        var sw = Stopwatch.StartNew();
        const int V1 = 0xfffff;
        for (int i1 = 0; i1 < V1; i1++)
            for (int i = 0; i < V; i++)
            {
                mDict[new Flags(i)]++;
            }

        Console.WriteLine("m " + sw.ElapsedMilliseconds);

        sw.Restart();
        for (int i1 = 0; i1 < V1; i1++)
            for (int i = 0; i < V; i++)
            {
                nDict[new Flags(i)]++;
            }

        Console.WriteLine(sw.ElapsedMilliseconds);

        sw.Restart();
        for (int i1 = 0; i1 < V1; i1++)
            for (int i = 0; i < V; i++)
            {
                mDict[new Flags(i)]++;
            }

        Console.WriteLine("m " + sw.ElapsedMilliseconds);

        sw.Restart();
        for (int i1 = 0; i1 < V1; i1++)
            for (int i = 0; i < V; i++)
            {
                nDict[new Flags(i)]++;
            }

        Console.WriteLine(sw.ElapsedMilliseconds);

        Console.ReadKey();
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : Alan-FGR

static void Measure(string previousMeasurement = null)
    {
        if (previousMeasurement != null) Console.WriteLine($"{sw.Elapsed.TotalMilliseconds:00.00} ms {previousMeasurement}");
        sw.Restart();
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : Alan-FGR

private static void StressMiniDict()
    {
        const int V = 20;
        var keys = new Flags[V];
        for (int i = 0; i < V; i++)
            keys[i] = new Flags(i);
        var mDict = new MiniDict<Flags, int>(keys);

        var nDict = new Dictionary<Flags, int>(V);


        for (int i = 0; i < V; i++)
        {
            mDict[new Flags(i)] = i;
        }

        for (int i = 0; i < V; i++)
        {
            nDict[new Flags(i)] = i;
        }

        var sw = Stopwatch.StartNew();
        const int V1 = 0xfffff;
        for (int i1 = 0; i1 < V1; i1++)
        for (int i = 0; i < V; i++)
        {
            mDict[new Flags(i)]++;
        }

        Console.WriteLine("m " + sw.ElapsedMilliseconds);

        sw.Restart();
        for (int i1 = 0; i1 < V1; i1++)
        for (int i = 0; i < V; i++)
        {
            nDict[new Flags(i)]++;
        }

        Console.WriteLine(sw.ElapsedMilliseconds);

        sw.Restart();
        for (int i1 = 0; i1 < V1; i1++)
        for (int i = 0; i < V; i++)
        {
            mDict[new Flags(i)]++;
        }

        Console.WriteLine("m " + sw.ElapsedMilliseconds);

        sw.Restart();
        for (int i1 = 0; i1 < V1; i1++)
        for (int i = 0; i < V; i++)
        {
            nDict[new Flags(i)]++;
        }

        Console.WriteLine(sw.ElapsedMilliseconds);

        Console.ReadKey();
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : Alan-FGR

public static void Time(string name, Action action)
    {
        sw.Restart();
        action.Invoke();
        timings.Add(name + ": " + sw.ElapsedMilliseconds + " ms");
        //timings.Add(name + ": " + sw.ElapsedTicks / (Stopwatch.Frequency / 1000000f) + "us");
    }

19 View Source File : Popup.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

public void Display()
        {
            if (!cleanGameFibersRunning)
            {
                cleanGameFibers();
            }
            hasDisplayed = false;
            IndexOfGivenAnswer = -1;
            popupQueue.Add(this);
            if (fiber != null && popupFibersToDelete.Contains(fiber))
            {
                popupFibersToDelete.Remove(fiber);
            }
            Game.LogTrivial("Adding " + Popupreplacedle + " popup to queue.");
            fiber = new GameFiber(delegate
            {
                
                while (!ForceDisplay)
                {
                    GameFiber.Yield();
                    if (!CommonVariables.DisplayTime && !Game.IsPaused)
                    {
                        if (popupQueue.Count > 0 && popupQueue[0] == this)
                        {
                            break;
                        }
                        else if (popupQueue.Count == 0)
                        {
                            break;
                        }
                    }
                }

                CommonVariables.DisplayTime = true;
                if (PauseGame)
                {
                    Game.IsPaused = true;
                }
                if (showEnterConfirmation)
                {
                    popupLines.AddRange(("Press Enter to close.").WrapText(720, "Arial Bold", 15.0f, out PopupTextLineHeight));
                }
                isDisplaying = true;
                GameFiber.Sleep(Delay);
                popupQueue.Remove(this);
                Game.RawFrameRender += DrawPopup;
                Game.LogTrivial("Drawing " + Popupreplacedle + " popup message");

                timer.Restart();
                if (showEnterConfirmation)
                {
                    while (isDisplaying)
                    {
                        if (PauseGame)
                        {
                            Game.IsPaused = true;
                        }
                        GameFiber.Yield();
                        if (timer.ElapsedMilliseconds > 25000)
                        {
                            Game.DisplayNotification("A textbox is currently being shown in the centre of your screen. If you can't see it, RPH had an issue initializing with DirectX and your RPH console won't work either - ask for support on the RPH Discord (link at www.ragepluginhook.net");
                            timer.Restart();
                        }
                        if (Game.IsKeyDown(Keys.Enter))
                        {
                            Game.LogTrivial("ClosePopup is pressed");
                            Hide();
                            break;
                        }
                    }
                }

                else if (Answers != null && Answers.Count > 0)
                {
                    while (isDisplaying)
                    {
                        if (PauseGame)
                        {
                            Game.IsPaused = true;
                        }
                        GameFiber.Yield();
                        if (timer.ElapsedMilliseconds > 25000)
                        {
                            Game.DisplayNotification("A textbox is currently being shown in the centre of your screen. If you can't see it, RPH had an issue initializing with DirectX and your RPH console won't work either - ask for support on the RPH Discord (link at www.ragepluginhook.net");
                            timer.Restart();
                        }

                        if (Game.IsKeyDown(Keys.D1))
                        {
                            if (answersAsDisplayed.Count >= 1)
                            {
                                IndexOfGivenAnswer = Answers.IndexOf(answersAsDisplayed[0]);
                                Hide();

                            }
                        }
                        if (Game.IsKeyDown(Keys.D2))
                        {
                            if (answersAsDisplayed.Count >= 2)
                            {
                                IndexOfGivenAnswer = Answers.IndexOf(answersAsDisplayed[1]);
                                Hide();
                            }
                        }
                        if (Game.IsKeyDown(Keys.D3))
                        {
                            if (answersAsDisplayed.Count >= 3)
                            {
                                IndexOfGivenAnswer = Answers.IndexOf(answersAsDisplayed[2]);
                                Hide();
                            }
                        }
                        if (Game.IsKeyDown(Keys.D4))
                        {
                            if (answersAsDisplayed.Count >= 4)
                            {
                                IndexOfGivenAnswer = Answers.IndexOf(answersAsDisplayed[3]);
                                Hide();
                            }
                        }
                        if (Game.IsKeyDown(Keys.D5))
                        {
                            if (answersAsDisplayed.Count >= 5)
                            {
                                IndexOfGivenAnswer = Answers.IndexOf(answersAsDisplayed[4]);
                                Hide();
                            }
                        }
                        if (Game.IsKeyDown(Keys.D6))
                        {
                            if (answersAsDisplayed.Count >= 6)
                            {
                                IndexOfGivenAnswer = Answers.IndexOf(answersAsDisplayed[5]);
                                Hide();
                            }
                        }
                    }
                }
                timer.Stop();
            });
            fiber.Start();
            
            
        }

19 View Source File : RequestPit.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

public static void Main()
        {
            //if (pitRequestActive) { Game.LogTrivial("PIT request already active"); return; }
            GameFiber.StartNew(delegate
            {
                
                if (!Game.LocalPlayer.Character.IsInAnyVehicle(false)) { return; }
                if (Functions.GetActivePursuit() == null) { return; }
                List<Ped> eligiblePeds = Functions.GetPursuitPeds(Functions.GetActivePursuit()).Where(x => x.DistanceTo(Game.LocalPlayer.Character) < 55f && x.IsInAnyVehicle(false)).ToList();
                Game.LogTrivial(eligiblePeds.Count.ToString());
                if (eligiblePeds.Count > 0)
                {
                    Vehicle targetVeh = eligiblePeds.OrderBy(x => x.DistanceTo(Game.LocalPlayer.Character.GetOffsetPositionFront(4f))).First().CurrentVehicle;
                    Ped targetPed = targetVeh.Driver;
                    Vehicle[] nearbyVehs = targetPed.Exists() ? targetPed.GetNearbyVehicles(16) : Game.LocalPlayer.Character.GetNearbyVehicles(16);

                    int NearbyOccupiedCivilianVehsCount = 0;
                    foreach (Vehicle veh in nearbyVehs)
                    {
                        if (veh.Exists())
                        {
                            if (veh.HasDriver)
                            {
                                if (!veh.Hreplacediren)
                                {
                                    NearbyOccupiedCivilianVehsCount++;
                                }
                            }
                        }
                    }
                    Game.DisplayNotification("~b~" + PoliceSmartRadio.PlayerName + "~s~: Dispatch, requesting to perform ~r~PIT~s~.");

                    if (NearbyOccupiedCivilianVehsCount > 7)
                    {
                        GameFiber.Wait(4000);
                        Game.DisplayNotification("~b~Dispatch ~w~: " + PoliceSmartRadio.PlayerName + ", traffic is ~r~too busy.~s~ You ~r~aren't clear~s~ to ~r~PIT, ~w~over.");
                        return;
                    }
                    else
                    {
                        GameFiber.Wait(4000);
                        Game.DisplayNotification("~b~Dispatch ~w~: " + PoliceSmartRadio.PlayerName + " you are clear at this time to ~r~PIT, ~w~over.");
                    }

                    bool pitComplete = false;
                    Stopwatch standstillStopwatch = new Stopwatch();
                    standstillStopwatch.Start();
                    while (!pitComplete)
                    {
                        GameFiber.Yield();
                        if ((targetVeh.Speed <= 0.8f) && (Vector3.Distance(targetVeh.Position, Game.LocalPlayer.Character.Position) < 18f))
                        {
                            if (standstillStopwatch.ElapsedMilliseconds > 3500)
                            {
                                targetVeh.EngineHealth = 0.0f;
                                Game.DisplayNotification("~b~" + PoliceSmartRadio.PlayerName + "~s~: PIT successful, located at~b~ " + World.GetStreetName(Game.LocalPlayer.Character.Position));
                                pitComplete = true;
                            }
                        }
                        else
                        {
                            standstillStopwatch.Restart();
                        }

                        if (!targetVeh.HasDriver)
                        {
                            break;
                        }
                        
                    }
                }
            });
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : alchemz

public static void Main(string[] args)
        {
            Common.DV_Client client = new Common.DV_Client("127.0.0.1", 9001);
            double rightAscensionSpeed = 0.33f;
            double declinationSpeed = 0.1f;
            double rightAscension = 0;
            double declination = -1;
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            Task.Run(async () =>
            {
                while (true)
                {
                    var elapsed = stopwatch.Elapsed;
                    stopwatch.Restart();

                    rightAscension += elapsed.TotalSeconds * rightAscensionSpeed;
                    declination += elapsed.TotalSeconds * declinationSpeed;

                    while (rightAscension > 1)
                    {
                        rightAscension -= 1;
                    }
                    while (declination > 1)
                    {
                        declination -= 2;
                    }

                    var dataPoint = new DataPointViewModel()
                    {
                        color = new DataPointColor(),
                        rightAscension = (float)rightAscension,
                        declination = (float)declination
                    };
                    var message = JsonConvert.SerializeObject(dataPoint);
                    Console.WriteLine("Sending message {0}", message);
                    await client.SendMessageToServerTaskAsync(message);
                }
            }).Wait();
        }

19 View Source File : LSPDFRPlusHandler.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

private static void MainLoop()
        {
            GameFiber.StartNew(delegate
            {
                Game.LogTrivial("LSPDFR+ has been initialised successfully and is now loading INI, XML and dependencies. Standby...");
                AppDomain.CurrentDomain.replacedemblyResolve += new ResolveEventHandler(LSPDFRResolveEventHandler);
                GameFiber.Sleep(5000);
                BritishPolicingScriptRunning = IsLSPDFRPluginRunning("British Policing Script", new Version("0.9.0.0"));
                ArrestManagerRunning = IsLSPDFRPluginRunning("Arrest Manager", new Version("7.6.8.0"));
                TrafficPolicerRunning = IsLSPDFRPluginRunning("Traffic Policer", new Version("6.13.6.0"));
                if (BritishPolicingScriptRunning)
                {
                    API.BritishPolicingScriptFunctions.RegisterBPSOutOfVehicleEvent();
                    Offence.currency = "£";
                }
                if (ArrestManagerRunning)
                {
                    API.ArrestManagerFuncs.PlayerArrestedPedHandler();
                }
                else
                {
                    Game.DisplayNotification("To optimally use LSPDFR+, you are advised to install Arrest Manager by Albo1125.");
                }

                if (!TrafficPolicerRunning)
                {
                    Game.DisplayNotification("To optimally use LSPDFR+, you are advised to install Traffic Policer by Albo1125.");
                }

                Offence.DeserializeOffences();
                Game.LogTrivial("TrafficOffences:");
                Offence.CategorizedTrafficOffences.Values.ToList().ForEach(x => x.ForEach(y => Game.LogTrivial(y.ToString())));
                Menus.InitialiseMenus();

                CourtSystem.CourtSystemMainLogic();
                
                EnhancedPursuitAI.MainLoop();
                StatisticsCounter.AddCountToStatistic("Times gone on duty", "LSPDFR+");
                
                Game.LogTrivial("LSPDFR+ has been fully initialised successfully and is now working.");
                
                TimeOnDutyStopWatch.Start();
                while (true)
                {
                    GameFiber.Yield();

                    if (Functions.IsPlayerPerformingPullover() && NativeFunction.Natives.UPDATE_ONSCREEN_KEYBOARD<int>() == 0)
                    {
                        Game.DisplaySubreplacedle("~h~Stopped Vehicle: " + Functions.GetPulloverSuspect(Functions.GetCurrentPullover()).CurrentVehicle.LicensePlate, 50);
                    }

                    if (Game.IsPaused && TimeOnDutyStopWatch.IsRunning)
                    {
                        TimeOnDutyStopWatch.Stop();
                    }
                    else if (!Game.IsPaused && !TimeOnDutyStopWatch.IsRunning)
                    {
                        TimeOnDutyStopWatch.Start();
                    }

                    if (TimeOnDutyStopWatch.ElapsedMilliseconds > 60000)
                    {
                        StatisticsCounter.AddCountToStatistic("Minutes spent on duty", "LSPDFR+");
                        
                        TimeOnDutyStopWatch.Restart();
                    }
                    



                }
            });

        }

19 View Source File : Pow.cs
License : MIT License
Project Creator : alexanderdna

public static byte[] Hash(Stream stream)
        {
            using var hashAlgo = SHA256.Create();
            stream.Seek(0, SeekOrigin.Begin);
            sw.Restart();
            var hash = hashAlgo.ComputeHash(stream);
            sw.Stop();
            return hash;
        }

19 View Source File : Peer.cs
License : MIT License
Project Creator : aljazsim

private void Download()
        {
            TimeSpan timeout = TimeSpan.FromMilliseconds(250);
            TimeSpan chokeTimeout = TimeSpan.FromSeconds(10);
            Stopwatch stopwatch = Stopwatch.StartNew();
            PieceMessage pm;
            Piece piece = null;
            bool[] bitFieldData = Array.Empty<bool>();
            byte[] pieceData = Array.Empty<byte>();
            int unchokeMessagesSent = 0;

            if (!this.isDownloading)
            {
                this.isDownloading = true;

                this.communicator.PieceData = new byte[this.pieceManager.PieceLength];

                while (!this.IsDisposed)
                {
                    if (this.pieceManager.IsComplete)
                    {
                        break;
                    }

                    // process messages
                    foreach (PeerMessage message in this.DequeueDownloadMessages())
                    {
                        if (message is PieceMessage)
                        {
                            pm = message as PieceMessage;

                            if (piece != null &&
                                piece.PieceIndex == pm.PieceIndex &&
                                piece.BitField[pm.BlockOffset / this.pieceManager.BlockLength] == false)
                            {
                                // update piece
                                piece.PutBlock(pm.BlockOffset);

                                if (piece.IsCompleted ||
                                    piece.IsCorrupted)
                                {
                                    // remove piece in order to start a next one
                                    piece = null;
                                }
                            }
                        }
                        else if (message is ChokeMessage)
                        {
                            this.SeedingState = SeedingState.Choked;

                            piece = null;
                        }
                        else if (message is UnchokeMessage)
                        {
                            this.SeedingState = SeedingState.Unchoked;

                            unchokeMessagesSent = 0;
                        }
                    }

                    if (this.HandshakeState == HandshakeState.SendAndReceived)
                    {
                        if (this.SeedingState == SeedingState.Choked)
                        {
                            if (stopwatch.Elapsed > chokeTimeout)
                            {
                                // choked -> send interested
                                this.EnqueueSendMessage(new InterestedMessage());

                                if (++unchokeMessagesSent > 10)
                                {
                                    this.OnCommunicationErrorOccurred(this, new PeerCommunicationErrorEventArgs($"Choked for more than {TimeSpan.FromSeconds(chokeTimeout.TotalSeconds * 10)}.", true));
                                }

                                stopwatch.Restart();
                            }
                            else
                            {
                                Thread.Sleep(timeout);
                            }
                        }
                        else if (this.SeedingState == SeedingState.Unchoked)
                        {
                            if (piece == null)
                            {
                                // find a missing piece
                                for (int pieceIndex = 0; pieceIndex < this.BitField.Length; pieceIndex++)
                                {
                                    if (this.pieceManager.BitField[pieceIndex] == PieceStatus.Missing)
                                    {
                                        if (this.BitField[pieceIndex] ||
                                            this.pieceManager.IsEndGame)
                                        {
                                            pieceData = pieceData.Length == this.pieceManager.GetPieceLength(pieceIndex) ? pieceData : new byte[this.pieceManager.GetPieceLength(pieceIndex)];
                                            bitFieldData = bitFieldData.Length == this.pieceManager.GetBlockCount(pieceIndex) ? bitFieldData : new bool[this.pieceManager.GetBlockCount(pieceIndex)];

                                            // check it out
                                            piece = this.pieceManager.CheckOut(pieceIndex, pieceData, bitFieldData);

                                            if (piece != null)
                                            {
                                                this.communicator.PieceData = pieceData;

                                                break;
                                            }
                                        }
                                    }
                                }

                                if (piece != null)
                                {
                                    // request blocks from the missing piece
                                    for (int i = 0; i < piece.BitField.Length; i++)
                                    {
                                        if (!piece.BitField[i])
                                        {
                                            this.EnqueueSendMessage(new RequestMessage(piece.PieceIndex, (int)piece.GetBlockOffset(i), (int)piece.GetBlockLength(piece.GetBlockOffset(i))));
                                        }
                                    }
                                }
                            }
                        }
                    }

                    Thread.Sleep(timeout);
                }

                this.isDownloading = false;
            }
        }

19 View Source File : Peer.cs
License : MIT License
Project Creator : aljazsim

private void UpdateTrafficParameters(long downloaded, long uploaded)
        {
            downloaded.MustBeGreaterThanOrEqualTo(0);
            uploaded.MustBeGreaterThanOrEqualTo(0);

            lock (this.locker)
            {
                this.previouslyDownloaded += downloaded;
                this.previouslyUploaded += uploaded;

                if (this.stopwatch.Elapsed > TimeSpan.FromSeconds(1))
                {
                    this.downloadSpeed = (decimal)this.previouslyDownloaded / (decimal)this.stopwatch.Elapsed.TotalSeconds;
                    this.uploadSpeed = (decimal)this.previouslyUploaded / (decimal)this.stopwatch.Elapsed.TotalSeconds;

                    this.Downloaded += this.previouslyDownloaded;
                    this.Uploaded += this.previouslyUploaded;

                    this.previouslyDownloaded = 0;
                    this.previouslyUploaded = 0;

                    this.stopwatch.Restart();
                }
            }
        }

19 View Source File : ThrottlingManager.cs
License : MIT License
Project Creator : aljazsim

public void Read(long bytesRead)
        {
            bytesRead.MustBeGreaterThanOrEqualTo(0);

            decimal wait;

            lock (this.readingLocker)
            {
                if (!this.readStopwatch.IsRunning)
                {
                    this.readStopwatch.Start();
                }

                this.read += bytesRead;

                if (this.read > this.readDelta)
                {
                    this.readStopwatch.Stop();

                    this.ReadSpeed = this.read / (decimal)this.readStopwatch.Elapsed.TotalSeconds;

                    wait = (this.read / this.readDelta) * this.minReadTime;
                    wait = wait - this.readStopwatch.ElapsedMilliseconds;

                    if (wait > 0)
                    {
                        Thread.Sleep((int)Math.Round(wait));
                    }

                    this.read = 0;
                    this.readStopwatch.Restart();
                }
            }
        }

19 View Source File : ThrottlingManager.cs
License : MIT License
Project Creator : aljazsim

public void Write(long bytesWritten)
        {
            bytesWritten.MustBeGreaterThanOrEqualTo(0);

            decimal wait;

            lock (this.writingLocker)
            {
                if (!this.writeStopwatch.IsRunning)
                {
                    this.writeStopwatch.Start();
                }

                this.written += bytesWritten;

                if (this.written > this.writeDelta)
                {
                    this.writeStopwatch.Stop();

                    this.WriteSpeed = this.written / (decimal)this.writeStopwatch.Elapsed.TotalSeconds;

                    wait = (this.written / this.writeDelta) * this.minWriteTime;
                    wait = wait - this.writeStopwatch.ElapsedMilliseconds;

                    if (wait > 0)
                    {
                        Thread.Sleep((int)Math.Round(wait));
                    }

                    this.written = 0;
                    this.writeStopwatch.Restart();
                }
            }
        }

19 View Source File : PerformanceAnalyze.cs
License : MIT License
Project Creator : AlturosDestinations

private void Check(GpuConfig gpuConfig)
        {
            var yoloWrapper = new YoloWrapper("yolov2-tiny-voc.cfg", "yolov2-tiny-voc.weights", "voc.names", gpuConfig);
            var files = Directory.GetFiles(@".\Images");

            var retrys = 10;

            var sw = new Stopwatch();
            foreach (var file in files)
            {
                var elapsed = 0.0;
                var fileInfo = new FileInfo(file);
                var imageData = File.ReadAllBytes(file);

                for (var i = 0; i < retrys; i++)
                {
                    sw.Restart();
                    yoloWrapper.Detect(imageData);
                    sw.Stop();

                    elapsed += sw.Elapsed.TotalMilliseconds;
                }

                var average = elapsed / retrys;
                Console.WriteLine($"{fileInfo.Name} {average}ms");
            }

            yoloWrapper.Dispose();
        }

19 View Source File : PerformanceResizeAnalyze.cs
License : MIT License
Project Creator : AlturosDestinations

private Tuple<List<YoloItem>, string, string, double> ProcessResizeBefore(YoloWrapper yoloWrapper, ImageResizer imageResize, byte[] imageData)
        {
            var sw = new Stopwatch();
            sw.Start();
            imageData = imageResize.Resize(imageData, 416, 416);
            sw.Stop();
            var resizeElapsed = sw.Elapsed.TotalMilliseconds;
            sw.Restart();
            var items = yoloWrapper.Detect(imageData).ToList();
            sw.Stop();

            return new Tuple<List<YoloItem>, string, string, double>(items, $"{resizeElapsed:0.00}", $"{sw.Elapsed.TotalMilliseconds:0.00}", sw.Elapsed.TotalMilliseconds + resizeElapsed);
        }

19 View Source File : HighResolutionTimer.cs
License : MIT License
Project Creator : andruzzzhka

private void ExecuteTimer()
        {
            float nextTrigger = 0f;

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            while (_isRunning)
            {
                nextTrigger += _interval;
                double elapsed;

                while (true)
                {
                    elapsed = ElapsedHiRes(stopwatch);
                    double diff = nextTrigger - elapsed;
                    if (diff <= 0f)
                        break;

                    if (diff < 1f)
                        Thread.SpinWait(10);
                    else
                        Thread.Sleep(Math.Floor(diff));

                    if (!_isRunning)
                        return;
                }


                double delay = elapsed - nextTrigger;

                if (Elapsed != null)
                {
                    foreach (EventHandler<HighResolutionTimerElapsedEventArgs> nextDel in Elapsed.GetInvocationList())
                    {
                        try
                        {
                            nextDel.Invoke(this, new HighResolutionTimerElapsedEventArgs(delay));
                        }
                        catch (Exception e)
                        {
                            if (Settings.Instance.Server.ShowTickEventExceptions)
                                Logger.Instance.Exception($"Exception in {nextDel.Method.Name} on tick event: {e}");
                        }
                    }
                }

                if (AfterElapsed != null)
                {
                    foreach (EventHandler<HighResolutionTimerElapsedEventArgs> nextDel in AfterElapsed.GetInvocationList())
                    {
                        try
                        {
                            nextDel.Invoke(this, new HighResolutionTimerElapsedEventArgs(delay));
                        }
                        catch (Exception e)
                        {
                            if (Settings.Instance.Server.ShowTickEventExceptions)
                                Logger.Instance.Exception($"Exception in {nextDel.Method.Name} on tick event: {e}");
                        }
                    }
                }

                if (!_isRunning)
                    return;

                // restarting the timer in every hour to prevent precision problems
                if (stopwatch.Elapsed.TotalHours >= 1d)
                {
                    stopwatch.Restart();
                    nextTrigger = 0f;
                }
            }

            stopwatch.Stop();
        }

See More Examples