System.Diagnostics.Stopwatch.StartNew()

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

3129 Examples 7

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

[Test]
        public async Task Test_OldWay()
        {
            var sw = Stopwatch.StartNew();

            Task<int> get1 = Get1();
            Task<int> get2 = Get2();
            Task<string> get3Str = Get3Str();
            Task<int> get4 = Get4();

            await Task.WhenAll(get1, get2, get3Str, get4);

            var result = get1.Result + get2.Result + int.Parse(get3Str.Result) + get4.Result;


            sw.Stop();

            replacedert.AreEqual(9, result);
            replacedert.GreaterOrEqual(sw.ElapsedMilliseconds, TimeSlotMs);
            replacedert.Less(sw.ElapsedMilliseconds, TimeSlotMs + LagMs);
        }

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

[Test]
        public async Task Test_ParallelOnly()
        {
            var sw = Stopwatch.StartNew();

            var result = await
                from val1  in Get1().AsParallel()
                from val2  in Get2().AsParallel()
                from val3S in Get3Str().AsParallel()
                from val4  in Get4().AsParallel()
                select val1 + val2 + int.Parse(val3S) + val4;


            sw.Stop();

            replacedert.AreEqual(9, result);
            replacedert.GreaterOrEqual(sw.ElapsedMilliseconds, TimeSlotMs);
            replacedert.Less(sw.ElapsedMilliseconds, TimeSlotMs + LagMs);
        }

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

[Test]
        public async Task Test_SequentialAndLet()
        {
            var sw = Stopwatch.StartNew();

            var result = await
                from one in Get1().AsParallel()

                let oneA = one

                from two in Get2().AsParallel()
                from freeStr in Get3Str().AsParallel()

                let free = int.Parse(freeStr)//Intermediate expr 

                from eight in  Add5(free).replacedequential()//Here all the previous results can be used

                from oneB in Get1().AsParallel()
                from twoA in Get2().AsParallel()
                
                from six in Add5(oneB).replacedequential()//Here all the previous results can be used 
                
                select one + oneA + two + int.Parse(freeStr) + free + eight + oneB + twoA + six;


            sw.Stop();

            replacedert.AreEqual(27, result);
            replacedert.GreaterOrEqual(sw.ElapsedMilliseconds, TimeSlotMs*3);
            replacedert.Less(sw.ElapsedMilliseconds, TimeSlotMs*3 + LagMs);
        }

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

[Test]
        public async Task Test_ParallelAndLet()
        {
            var sw = Stopwatch.StartNew();

            var result = await
                from one in Get1().AsParallel()

                let oneA = one

                from two in Get2().AsParallel()
                from freeStr in Get3Str().AsParallel()

                let free = int.Parse(freeStr)//Intermediate expr 

                from oneB in Get1().AsParallel()
                from twoA in Get2().AsParallel()
                
                select one + oneA + two + int.Parse(freeStr) + free + oneB + twoA;


            sw.Stop();

            replacedert.AreEqual(13, result);
            replacedert.GreaterOrEqual(sw.ElapsedMilliseconds, TimeSlotMs);
            replacedert.Less(sw.ElapsedMilliseconds, TimeSlotMs + LagMs);
        }

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

[Test]
        public async Task Test_Error()
        {
            var sw = Stopwatch.StartNew();

            var task =
                from val1 in Get1().AsParallel()
                from val2 in Get2().AsParallel()
                from err in Error(1).AsParallel()
                from val4 in Get4().AsParallel()
                from error3 in Error(3).replacedequential() 
                from err2 in Error(2).AsParallel()
                select val1 + val2  + val4;

            Exception exception = null;
            try
            {
                await task;
            }
            catch (Exception e)
            {
                exception = e;
            }

            replacedert.NotNull(exception);
            replacedert.AreEqual("This is a test error #1", exception.Message);


            sw.Stop();

            replacedert.GreaterOrEqual(sw.ElapsedMilliseconds, TimeSlotMs);
            replacedert.Less(sw.ElapsedMilliseconds, TimeSlotMs + LagMs);
        }

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

[Test]
        public async Task Test_ErrorInSelect()
        {
            var sw = Stopwatch.StartNew();

            var task =
                from val1 in Get1().AsParallel()
                from val2 in Get2().AsParallel()
                from val4 in Get4().AsParallel()

                select val1 == 1 ? throw new Exception("This is a test error #2") : val1 + val2  + val4;

            Exception exception = null;
            try
            {
                await task;
            }
            catch (Exception e)
            {
                exception = e;
            }

            replacedert.NotNull(exception);
            replacedert.AreEqual("This is a test error #2", exception.Message);


            sw.Stop();

            replacedert.GreaterOrEqual(sw.ElapsedMilliseconds, TimeSlotMs);
            replacedert.Less(sw.ElapsedMilliseconds, TimeSlotMs + LagMs);
        }

19 View Source File : CommandExecuteMonitor.cs
License : MIT License
Project Creator : 1100100

private TResult SyncCommandExecuteMonitor<TResult>(string methodName, string sql, object param, Func<TResult> func)
        {
            var sw = Stopwatch.StartNew();
            try
            {
                return func();
            }
            finally
            {
                sw.Stop();
                if (sw.ElapsedMilliseconds > MonitorConfiguration.SlowCriticalValue)
                {
                    SlowCommandNotification(methodName, sql, param, sw.ElapsedMilliseconds);
                }
            }
        }

19 View Source File : CommandExecuteMonitor.cs
License : MIT License
Project Creator : 1100100

private async Task<TResult> AsyncCommandExecuteMonitor<TResult>(string methodName, string sql, object param, Func<Task<TResult>> func)
        {
            var sw = Stopwatch.StartNew();
            try
            {
                return await func();
            }
            finally
            {
                sw.Stop();
                if (sw.ElapsedMilliseconds > MonitorConfiguration.SlowCriticalValue)
                {
                    SlowCommandNotification(methodName, sql, param, sw.ElapsedMilliseconds);
                }
            }
        }

19 View Source File : CommandExecuteMonitor.cs
License : MIT License
Project Creator : 1100100

private void SyncCommandExecuteMonitor(string methodName, string sql, object param, Action action)
        {
            var sw = Stopwatch.StartNew();
            try
            {
                action();
            }
            finally
            {
                sw.Stop();
                if (sw.ElapsedMilliseconds > MonitorConfiguration.SlowCriticalValue)
                {
                    SlowCommandNotification(methodName, sql, param, sw.ElapsedMilliseconds);
                }
            }
        }

19 View Source File : CommandExecuteMonitor.cs
License : MIT License
Project Creator : 1100100

private async Task AsyncCommandExecuteMonitor(string methodName, string sql, object param, Func<Task> action)
        {
            var sw = Stopwatch.StartNew();
            try
            {
                await action();
            }
            finally
            {
                sw.Stop();
                if (sw.ElapsedMilliseconds > MonitorConfiguration.SlowCriticalValue)
                {
                    SlowCommandNotification(methodName, sql, param, sw.ElapsedMilliseconds);
                }
            }
        }

19 View Source File : GCodeParser.cs
License : MIT License
Project Creator : 3RD-Dimension

public static void Parse(IEnumerable<string> file)
		{
			int i = 0;

			var sw = System.Diagnostics.Stopwatch.StartNew();

			foreach (string linei in file)
			{
				i++;
				string line = CleanupLine(linei, i);

				if (string.IsNullOrWhiteSpace(line))
					continue;

				Parse(line.ToUpper(), i);
			}

			sw.Stop();

            MainWindow.Logger.Info("parsing the G code file took {0} ms", sw.ElapsedMilliseconds);
		}

19 View Source File : GCodeFile.cs
License : MIT License
Project Creator : 3RD-Dimension

public void GetModel(LinesVisual3D line, LinesVisual3D rapid, LinesVisual3D arc)
		{
			var sw = System.Diagnostics.Stopwatch.StartNew();

			Point3DCollection linePoints = new Point3DCollection();
			Point3DCollection rapidPoints = new Point3DCollection();
			Point3DCollection arcPoints = new Point3DCollection();

			foreach (Command c in Toolpath)
			{
				var l = c as Line;

				if (l != null)
				{
					if (l.Rapid)
					{
						rapidPoints.Add(l.Start.ToPoint3D());
						rapidPoints.Add(l.End.ToPoint3D());
					}
					else
					{
						linePoints.Add(l.Start.ToPoint3D());
						linePoints.Add(l.End.ToPoint3D());
					}

					continue;
				}

				var a = c as Arc;

				if (a != null)
				{
					foreach (Motion sub in a.Split(Settings.Default.ViewportArcSplit))
					{
						arcPoints.Add(sub.Start.ToPoint3D());
						arcPoints.Add(sub.End.ToPoint3D());
					}
				}
			}

			line.Points = linePoints;
			rapid.Points = rapidPoints;
			arc.Points = arcPoints;

			sw.Stop();
            MainWindow.Logger.Info("Generating the toolpath model took {0} ms", sw.ElapsedMilliseconds);
		}

19 View Source File : BitfinexSocketApi.cs
License : MIT License
Project Creator : aabiryukov

private BitfinexApiResult<long> WaitSubscription(BitfinexEventRegistration registration)
        {
            var sw = Stopwatch.StartNew();
            if (!registration.CompleteEvent.WaitOne(3000))
            {
                lock(eventListLock)
                    eventRegistrations.Remove(registration);
                return ThrowErrorMessage<long>(BitfinexErrors.GetError(BitfinexErrorKey.SubscriptionNotConfirmed));
            }
            sw.Stop();
            Log.Write(LogVerbosity.Info, $"Wait took {sw.ElapsedMilliseconds}ms");

            if (registration.Confirmed)
                return ReturnResult(registration.Id);

            lock(eventListLock)
                eventRegistrations.Remove(registration);
            return ThrowErrorMessage<long>(registration.Error);            
        }

19 View Source File : IntegrationTests.cs
License : MIT License
Project Creator : Abc-Arbitrage

[Test]
        public void should_test_append()
        {

            Console.WriteLine("Starting test");
            var sw = Stopwatch.StartNew();

            Parallel.For(0, _nbThreads, threadId =>
            {
                var logger = LogManager.GetLogger(typeof(IntegrationTests).Name + threadId.ToString());
                for (var i = 0; i < _count; i++)
                {
                    var timestamp = Stopwatch.GetTimestamp();
                    logger.InfoFormat("{0}", timestamp);
                    _enqueueMicros[threadId][i] = ToMicroseconds(Stopwatch.GetTimestamp() - timestamp);
                }
            });

            LogManager.Shutdown();
            var throughput = _count / sw.Elapsed.TotalSeconds;

            Console.WriteLine($"Finished test, throughput is: {throughput:N0} msgs/second");

            _performanceAppender.PrintTimeTaken();

            var streamWriter = new StreamWriter(new FileStream("write-times.csv", FileMode.Create));
            foreach (var thread in _enqueueMicros)
            {
                foreach (var timeTaken in thread)
                {
                    streamWriter.WriteLine(timeTaken);
                }
            }
            Console.WriteLine("Printed total time taken csv");
        }

19 View Source File : IntegrationTests.cs
License : MIT License
Project Creator : Abc-Arbitrage

[Test]
        public void should_not_allocate()
        {
            const int count = 1000000;

            GC.Collect(2, GCCollectionMode.Forced, true);
            var timer = Stopwatch.StartNew();
            var gcCount = GC.CollectionCount(0);

            var logger = LogManager.GetLogger(typeof(IntegrationTests));
            for (var i = 0; i < count; i++)
            {
                Thread.Sleep(1);
                logger.Info().Append("Hello").Log();
            }

            LogManager.Shutdown();
            var gcCountAfter = GC.CollectionCount(0);
            timer.Stop();

            Console.WriteLine("BCL  : {0} us/log", timer.ElapsedMilliseconds * 1000.0 / count);
            Console.WriteLine("GCs  : {0}", gcCountAfter - gcCount);
        }

19 View Source File : Wait.cs
License : MIT License
Project Creator : Abc-Arbitrage

public static void Until([InstantHandle] Func<bool> exitCondition, TimeSpan timeout)
        {
            var sw = Stopwatch.StartNew();

            while (sw.Elapsed < timeout)
            {
                if (exitCondition())
                    return;

                Thread.Sleep(10);
            }

            throw new TimeoutException();
        }

19 View Source File : ThroughputToFileBench.cs
License : MIT License
Project Creator : Abc-Arbitrage

public static void Run()
        {
            var dir = Path.GetFullPath(Guid.NewGuid().ToString());
            Directory.CreateDirectory(dir);

            try
            {
                Console.WriteLine("Initializing...");

                BasicConfigurator.Configure(
                    new ZeroLogBasicConfiguration
                    {
                        Appenders = { new DateAndSizeRollingFileAppender(Path.Combine(dir, "Output")), },
                        LogEventQueueSize = 1000 * 4096 * 4,
                        LogEventPoolExhaustionStrategy = LogEventPoolExhaustionStrategy.WaitForLogEvent
                    }
                );

                var log = LogManager.GetLogger(typeof(ThroughputToFileBench));
                var duration = TimeSpan.FromSeconds(10);

                Console.WriteLine("Starting...");

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();

                var sw = Stopwatch.StartNew();
                long counter = 0;
                while (sw.Elapsed < duration)
                {
                    counter++;
                    log.Debug().Append("Counter is: ").Append(counter).Log();
                }

                Console.WriteLine($"Log events: {counter:N0}, Time to append: {sw.Elapsed}");
                Console.WriteLine("Flushing...");
                LogManager.Shutdown();
                Console.WriteLine($"Time to flush: {sw.Elapsed}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Directory.Delete(dir, true);
            }

            Console.WriteLine("Done");
        }

19 View Source File : PerformanceTests.cs
License : MIT License
Project Creator : Abc-Arbitrage

[Test]
        public void should_run_test()
        {
            const int threadMessageCount = 1000 * 1000;
            const int threadCount = 5;
            const int totalMessageCount = threadMessageCount * threadCount;

            var timer = Stopwatch.StartNew();

            var logger = LogManager.GetLogger(typeof(PerformanceTests));

            var signal = _testAppender.SetMessageCountTarget(totalMessageCount);
            var utcNow = DateTime.UtcNow;

            Parallel.For(0, threadCount, i =>
            {
                for (var k = 0; k < threadMessageCount; k++)
                {
                    logger.Info().Append("Hello ").Append(42).Append(utcNow).Append(42.56).Append(" this is a relatlively long message ").Append(12345.4332m).Log();
                }
            });

            var timedOut = !signal.Wait(TimeSpan.FromSeconds(10));

            timer.Stop();
            if (timedOut)
                replacedert.Fail("Timeout");

            Console.WriteLine($"Total message count  : {totalMessageCount:N0} messages");
            Console.WriteLine($"Thread message count : {threadMessageCount:N0} messages");
            Console.WriteLine($"Thread count         : {threadCount} threads");
            Console.WriteLine($"Elapsed time         : {timer.ElapsedMilliseconds:N0} ms");
            Console.WriteLine($"Message rate         : {totalMessageCount / timer.Elapsed.TotalSeconds:N0} m/s");
            Console.WriteLine($"Average log cost     : {timer.ElapsedMilliseconds * 1000 / (double)totalMessageCount:N3} µs");
        }

19 View Source File : SimRuntime.cs
License : MIT License
Project Creator : abdullin

public void Run(Func<SimControl, Task> plan) {
            _haltError = null;

            var watch = Stopwatch.StartNew();
            var reason = "none";
            
            Debug(LogType.RuntimeInfo,  $"{"start".ToUpper()}");
            Rand.Reinitialize(0);

            using (var cluster = new SimCluster(Def, this)) {
                
                Schedule(_scheduler,TimeSpan.Zero, _factory.StartNew(async () => {
                    var control = new SimControl(cluster, this);
                    try {
                        await plan(control);
                    } catch (Exception ex) {
                        Halt("Plan failed", ex);
                    }
                }));


                try {
                    var step = 0;
                    while (true) {
                        step++;

                        var hasFuture = FutureQueue.TryGetFuture(out var o);
                        if (!hasFuture) {
                            reason = "died";
                            break;
                        }

                        if (o.Time > _time) {
                            _time = o.Time;
                        }

                        switch (o.Item) {
                            case Task t:
                                o.Scheduler.Execute(t);
                                break;
                            default:
                                throw new InvalidOperationException();
                        }

                        if (_haltError != null || _haltMessage != null) {
                            reason = "halt";
                            break;
                        }

                        if ((_time - _lastActivity) >= _maxInactiveTicks) {
                            reason = "no activity " + Moment.Print(TimeSpan.FromTicks(_maxInactiveTicks));
                            break;
                        }

                        if (_steps >= MaxSteps) {
                            reason = MaxSteps + " steps reached";
                            break;
                        }

                        if (_time >= MaxTicks) {
                            reason = "max time";
                            break;
                        }
                    }
                } catch (Exception ex) {
                    reason = "fatal";
                    _haltError = ex;
                    Console.WriteLine("Fatal: " + ex);
                } finally {
                    if (_folder != null) {
                        Directory.Delete(_folder, true);
                    }
                }

                watch.Stop();

                var softTime = TimeSpan.FromTicks(_time);
                var factor = softTime.TotalHours / watch.Elapsed.TotalHours;

                if (_haltMessage != null) {
                    reason = _haltMessage.ToUpper();
                }

                Debug(LogType.RuntimeInfo,  $"{reason.ToUpper()} at {softTime}");

                if (_haltError != null) {
                    var demystify = _haltError.Demystify();
                    Console.WriteLine(demystify.GetType().Name + ": " + demystify.Message);
                    Console.WriteLine(demystify.StackTrace);
                }

                Console.WriteLine($"Simulated {Moment.Print(softTime)} in {_steps} steps.");
                Console.WriteLine($"Took {Moment.Print(watch.Elapsed)} of real time (x{factor:F0} speed-up)");
                // statistics
                
                Console.WriteLine($"Stats: {FutureQueue.JumpCount} jumps, {cluster.Machines.Sum(m => m.Value.SocketCount)} sockets");

            }

            

        }

19 View Source File : MeshSmoother.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static List<Vector3> CalculateSmoothNormals(Vector3[] vertices, Vector3[] normals)
        {
            var watch = System.Diagnostics.Stopwatch.StartNew();

            // Group all vertices that share the same location in space.
            var groupedVerticies = new Dictionary<Vector3, List<KeyValuePair<int, Vector3>>>();

            for (int i = 0; i < vertices.Length; ++i)
            {
                var vertex = vertices[i];
                List<KeyValuePair<int, Vector3>> group;

                if (!groupedVerticies.TryGetValue(vertex, out group))
                {
                    group = new List<KeyValuePair<int, Vector3>>();
                    groupedVerticies[vertex] = group;
                }

                group.Add(new KeyValuePair<int, Vector3>(i, vertex));
            }

            var smoothNormals = new List<Vector3>(normals);

            // If we don't hit the degenerate case of each vertex is it's own group (no vertices shared a location), average the normals of each group.
            if (groupedVerticies.Count != vertices.Length)
            {
                foreach (var group in groupedVerticies)
                {
                    var smoothingGroup = group.Value;

                    // No need to smooth a group of one.
                    if (smoothingGroup.Count != 1)
                    {
                        var smoothedNormal = Vector3.zero;

                        foreach (var vertex in smoothingGroup)
                        {
                            smoothedNormal += normals[vertex.Key];
                        }

                        smoothedNormal.Normalize();

                        foreach (var vertex in smoothingGroup)
                        {
                            smoothNormals[vertex.Key] = smoothedNormal;
                        }
                    }
                }
            }

            Debug.LogFormat("CalculateSmoothNormals took {0} ms on {1} vertices.", watch.ElapsedMilliseconds, vertices.Length);

            return smoothNormals;
        }

19 View Source File : OVRLipSyncMicInput.cs
License : MIT License
Project Creator : absurd-joy

public void StartMicrophone()
    {
        if (micSelected == false) return;

        //Starts recording
        audioSource.clip = Microphone.Start(selectedDevice, true, 1, micFrequency);

        Stopwatch timer = Stopwatch.StartNew();

        // Wait until the recording has started
        while (!(Microphone.GetPosition(selectedDevice) > 0) && timer.Elapsed.TotalMilliseconds < 1000) {
            Thread.Sleep(50);
        }

        if (Microphone.GetPosition(selectedDevice) <= 0)
        {
            throw new Exception("Timeout initializing microphone " + selectedDevice);
        }
        // Play the audio source
        audioSource.Play();
    }

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

private void OnTimerElapsed(object sender, EventArgs e)
        {
            if (_working) return;

            lock (_timer)
            {
                _working = true;

                // The simulation is very computationally expensive, so we update in parallel
                // What we observe is 400ms is required to update position of 1,000,000 elements
                var sw = Stopwatch.StartNew();
                _simulation.Tick(4);
                sw.Stop();
                //Console.WriteLine("Tick: {0}ms", sw.ElapsedMilliseconds);

                // By creating and filling a new series per-frame, we avoid the need
                // to call SuspendUpdates on the series, which will lock the parent chart.
                // 
                // Therefore we can append on another thread (other than UI Thread) and the UI will
                // draw the last series on the UI thread, while we are filling this series on the background thread
                // 
                // The trade-off is memory usage. Each time you create and discard an XyDataSeries you are putting additional
                // pressure on the garbage collector.                 

                var victims = _seriesPool.Get();
                var defenders = _seriesPool.Get();

                using (victims.SuspendUpdates())
                using (defenders.SuspendUpdates())
                {
                    victims.Clear();
                    defenders.Clear();

                    var persons = _simulation.People;
                    for (int i = 0; i < persons.Length; ++i)
                    {
                        Person person = persons[i];
                        if (person.IsVictim)
                            victims.Append(person.Pos.X, person.Pos.Y);
                        else
                            defenders.Append(person.Pos.X, person.Pos.Y);
                    }

                    _seriesPool.Put((XyDataSeries<double>) Victims);
                    _seriesPool.Put((XyDataSeries<double>) Defenders);
                    Victims = victims;
                    Defenders = defenders;
                }

                _working = false;
            }
        }

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

[SetUp]
        public void Setup()
        {
            _stopwatch = Stopwatch.StartNew();

            // Move mouse into top left corner of screen
            Mouse.Position = new System.Drawing.Point(0, 0);
        }

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

private void OnRunExample()
        {
            Task.Factory.StartNew(() =>
            {
                DataSeries = null;
                IsBusy = true;
                var stopwatch = Stopwatch.StartNew();

                // Generate Data and mark time                 
                var yData = new double[SeriesCount][];
                var generator = new RandomWalkGenerator(0d);
                for (int i = 0; i < SeriesCount; i++)
                {
                    yData[i] = generator.GetRandomWalkYData(PointCount);
                    generator.Reset();
                }

                stopwatch.Stop();
                IsBusy = false;

                // Append to SciChartSurface and mark time
                stopwatch = Stopwatch.StartNew();
                var allDataSeries = new IDataSeries[SeriesCount];
                for (int i = 0; i < SeriesCount; i++)
                {
                    var dataSeries = new UniformXyDataSeries<double>();
                    dataSeries.Append(yData[i]);
                    allDataSeries[i] = dataSeries;
                }

                DataSeries = allDataSeries;
                stopwatch.Stop();

                ViewportManager.AnimateZoomExtents(TimeSpan.FromMilliseconds(500));
            });
        }

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

private void OnRunExample()
        {
            Task.Factory.StartNew(() =>
            {
                DataSeries = null;

                // Generate Data and mark time 
                var dataSeries = new UniformXyDataSeries<double>();
                var stopwatch = Stopwatch.StartNew();
                var yData = new RandomWalkGenerator(0d).GetRandomWalkYData(Count);
                stopwatch.Stop();

                // Append to SciChartSurface and mark time
                stopwatch = Stopwatch.StartNew();
                dataSeries.Append(yData);
                DataSeries = dataSeries;
                stopwatch.Stop();

                // Zoom viewport to extents
                ViewportManager.AnimateZoomExtents(TimeSpan.FromMilliseconds(500));
            });
        }

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

public override void Run()
        {
            EventHandler tickHandler = null;
            tickHandler = (s, e) =>
                 {
                     _testCallback();

                     if (_stopWatch.ElapsedMilliseconds > _duration.TotalMilliseconds)
                     {
                         _stopWatch.Stop();
                         CompositionTarget.Rendering -= tickHandler;
                         double fps = _frameCount / _stopWatch.Elapsed.TotalSeconds;
                         _completedCallback(fps);
                     }
                 };
            _stopWatch = Stopwatch.StartNew();
            CompositionTarget.Rendering += tickHandler;
        }

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

public override void Run()
        {
            // NOTE: Uncomment this line to execute the Test Timer on a background thread. It makes a big difference to test performance
            // Why? Because Append is slow. Also DispatcherTimer is on the UI. It cannot run while the render takes place. 
            // I will profile the app with DispatcherTimer to see if there are any improvements. 
            // Meanwhile, you test with Threading.Timer as it will give you more accurate results
            
            //base.Run(); return;

            var timer = new DispatcherTimer();
            //timer.Interval = TimeSpan.FromMilliseconds(10); // 100Hz
            timer.Interval = TimeSpan.FromMilliseconds(0); //Arction 
            EventHandler tickHandler = null;
            tickHandler = (s, e) =>
                {
                    _testCallback();

                    if (_stopWatch.ElapsedMilliseconds > _duration.TotalMilliseconds)
                    {
                        _stopWatch.Stop();
                        timer.Tick -= tickHandler;
                        timer.Stop();
                        double fps = _frameCount / _stopWatch.Elapsed.TotalSeconds;
                        _completedCallback(fps);
                    }
                };

            timer.Tick += tickHandler;
            _stopWatch = Stopwatch.StartNew();
            timer.Start();
        }

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

public void Run()
        {
            _stopWatch = Stopwatch.StartNew();
            RunNext(_duration, _testCallback, _completedCallback);
        }

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

public virtual void Run()
        {
            timer = new Timer();
            timer.Interval = 10; // 100Hz
            //timer.Interval = 1; // 100Hz

            ElapsedEventHandler tickHandler = null;
            tickHandler = (s, e) =>
                {
                    _testCallback();

                    lock (this)
                    {
                        if (_stopped) return;
                        if (_stopWatch.ElapsedMilliseconds > _duration.TotalMilliseconds)
                        {
                            _stopWatch.Stop();
                            _stopped = true;
                            timer.Elapsed -= tickHandler;
                            timer.Stop();
                            double fps = _frameCount/_stopWatch.Elapsed.TotalSeconds;
                            Application.Current.Dispatcher.BeginInvoke(new Action(() => _completedCallback(fps)));
                        }
                    }
                };

            timer.Elapsed += tickHandler;
            _stopWatch = Stopwatch.StartNew();
            timer.Start();
        }

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

private static MutationFilter BuildMutation(string filename)
        {
            var lines = ReadScript(filename);

            if (lines == null)
            {
                log.Error($"MutationCache.BuildMutation({filename}) - embedded resource not found");
                return null;
            }

            string prevMutationLine = null;
            string mutationLine = null;

            var mutationFilter = new MutationFilter();
            Mutation mutation = null;
            MutationOutcome outcome = null;
            EffectList effectList = null;

            var totalChance = 0.0M;

            var timer = Stopwatch.StartNew();

            foreach (var _line in lines)
            {
                var line = _line;

                var commentIdx = line.IndexOf("//");

                if (commentIdx != -1)
                    line = line.Substring(0, commentIdx);

                if (line.Contains("Mutation #", StringComparison.OrdinalIgnoreCase))
                {
                    prevMutationLine = mutationLine;
                    mutationLine = line;
                    continue;
                }

                if (line.Contains("Tier chances", StringComparison.OrdinalIgnoreCase))
                {
                    if (outcome != null && outcome.EffectLists.Last().Chance != 1.0f)
                        log.Error($"MutationCache.BuildMutation({filename}) - {prevMutationLine} total {outcome.EffectLists.Last().Chance}, expected 1.0");

                    mutation = new Mutation();
                    mutationFilter.Mutations.Add(mutation);

                    var tierPieces = line.Split(',');

                    foreach (var tierPiece in tierPieces)
                    {
                        var match = Regex.Match(tierPiece, @"([\d.]+)");
                        if (match.Success && float.TryParse(match.Groups[1].Value, out var tierChance))
                        {
                            mutation.Chances.Add(tierChance);
                        }
                        else
                        {
                            log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse tier chances for {mutationLine}: {tierPiece}");
                            mutation.Chances.Add(0.0f);
                        }
                    }

                    outcome = new MutationOutcome();
                    mutation.Outcomes.Add(outcome);

                    totalChance = 0.0M;

                    continue;
                }

                if (line.Contains("- Chance", StringComparison.OrdinalIgnoreCase))
                {
                    if (totalChance >= 1.0M)
                    {
                        if (totalChance > 1.0M)
                            log.Error($"MutationCache.BuildMutation({filename}) - {mutationLine} total {totalChance}, expected 1.0");

                        outcome = new MutationOutcome();
                        mutation.Outcomes.Add(outcome);

                        totalChance = 0.0M;
                    }

                    effectList = new EffectList();
                    outcome.EffectLists.Add(effectList);

                    var match = Regex.Match(line, @"([\d.]+)");
                    if (match.Success && decimal.TryParse(match.Groups[1].Value, out var chance))
                    {
                        totalChance += chance / 100;

                        effectList.Chance = (float)totalChance;
                    }
                    else
                    {
                        log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {line} for {mutationLine}");
                    }
                    continue;
                }

                if (!line.Contains("="))
                    continue;

                var effect = new Effect();

                effect.Type = GetMutationEffectType(line);

                var firstOperator = GetFirstOperator(effect.Type);

                var pieces = line.Split(firstOperator, 2);

                if (pieces.Length != 2)
                {
                    log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {line}");
                    continue;
                }

                pieces[0] = pieces[0].Trim();
                pieces[1] = pieces[1].Trim();

                var firstStatType = GetStatType(pieces[0]);

                /*if (firstStatType == StatType.Undef)
                {
                    log.Error($"MutationCache.BuildMutation({filename}) - couldn't determine StatType for {pieces[0]} in {line}");
                    continue;
                }*/

                effect.Quality = ParseEffectArgument(filename, effect, pieces[0]);

                var hreplacedecondOperator = HreplacedecondOperator(effect.Type);

                if (!hreplacedecondOperator)
                {
                    effect.Arg1 = ParseEffectArgument(filename, effect, pieces[1]);
                }
                else
                {
                    var secondOperator = GetSecondOperator(effect.Type);

                    var subpieces = pieces[1].Split(secondOperator, 2);

                    if (subpieces.Length != 2)
                    {
                        log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {line}");
                        continue;
                    }

                    subpieces[0] = subpieces[0].Trim();
                    subpieces[1] = subpieces[1].Trim();

                    effect.Arg1 = ParseEffectArgument(filename, effect, subpieces[0]);
                    effect.Arg2 = ParseEffectArgument(filename, effect, subpieces[1]);
                }

                effectList.Effects.Add(effect);
            }

            if (outcome != null && outcome.EffectLists.Last().Chance != 1.0f)
                log.Error($"MutationCache.BuildMutation({filename}) - {mutationLine} total {outcome.EffectLists.Last().Chance}, expected 1.0");

            timer.Stop();

            // scripts take about ~2ms to compile
            //Console.WriteLine($"Compiled {filename} in {timer.Elapsed.TotalMilliseconds}ms");

            return mutationFilter;
        }

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

public static void UpdateTables(string path)
        {
            var timer = Stopwatch.StartNew();

            var types = Reflection.GetTypes("ACE.Server.Factories.Tables");

            var files = new Dictionary<string, Dictionary<string, object>>();

            ParseFolder(path, files);

            UpdateTables(types, files);

            timer.Stop();

            // ~0.2s
            Console.WriteLine();
            Console.WriteLine($"Updated loot tables in {timer.Elapsed.TotalSeconds}s");
            Console.WriteLine();
        }

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

public void LoadLandblock(uint landblockID, uint radius = 1)
        {
            Buffer.ClearBuffer();
            TextureCache.Init();

            LScape.unload_landblocks_all();

            var landblock = LScape.get_landblock(landblockID);
            if (landblock.IsDungeon)
                radius = 0;

            DungeonMode = landblock.IsDungeon;

            var center_lbx = landblockID >> 24;
            var center_lby = landblockID >> 16 & 0xFF;

            //Landblocks = new Dictionary<uint, R_Landblock>();
            R_Landblock r_landblock = null;
            R_Landblock centerBlock = null;

            for (var lbx = (int)(center_lbx - radius); lbx <= center_lbx + radius; lbx++)
            {
                if (lbx < 0 || lbx > 254) continue;

                for (var lby = (int)(center_lby - radius); lby <= center_lby + radius; lby++)
                {
                    if (lby < 0 || lby > 254) continue;

                    var lbid = (uint)(lbx << 24 | lby << 16 | 0xFFFF);

                    var timer = Stopwatch.StartNew();
                    landblock = LScape.get_landblock(lbid);
                    timer.Stop();

                    r_landblock = new R_Landblock(landblock);
                    //LScape.unload_landblock(lbid);

                    if (landblockID == lbid)
                        centerBlock = r_landblock;

                    MainWindow.Status.WriteLine($"Loaded {lbid:X8} in {timer.Elapsed.TotalMilliseconds}ms");

                    //Landblocks.Add(lbid, new R_Landblock(landblock));
                }
            }

            Buffer.BuildBuffers();

            if (DungeonMode)
            {
                BoundingBox = new Model.BoundingBox(Buffer.RB_EnvCell);
                Camera.InitDungeon(r_landblock, BoundingBox);
            }
            else
                Camera.InitLandblock(r_landblock);

            FreeResources();
        }

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

public async void LoadLandblocks(Vector2 startBlock, Vector2 endBlock)
        {
            Buffer.ClearBuffer();
            TextureCache.Init();
            
            LScape.unload_landblocks_all();

            DungeonMode = false;

            var dx = (int)(endBlock.X - startBlock.X) + 1;
            var dy = (int)(startBlock.Y - endBlock.Y) + 1;
            var numBlocks = dx * dy;

            var size = endBlock - startBlock;
            var center = startBlock + size / 2;
            var centerX = (uint)Math.Round(center.X);
            var centerY = (uint)Math.Round(center.Y);
            var landblockID = centerX << 24 | centerY << 16 | 0xFFFF;

            MainWindow.Status.WriteLine($"Loading {numBlocks} landblocks");
            await Task.Run(() => Thread.Sleep(50));

            //Landblocks = new Dictionary<uint, R_Landblock>();
            R_Landblock r_landblock = null;
            R_Landblock centerBlock = null;

            for (var lbx = (uint)startBlock.X; lbx <= endBlock.X; lbx++)
            {
                if (lbx < 0 || lbx > 254) continue;

                for (var lby = (uint)endBlock.Y; lby <= startBlock.Y; lby++)
                {
                    if (lby < 0 || lby > 254) continue;

                    var lbid = lbx << 24 | lby << 16 | 0xFFFF;

                    var timer = Stopwatch.StartNew();
                    var landblock = LScape.get_landblock(lbid);
                    timer.Stop();

                    r_landblock = new R_Landblock(landblock);
                    //LScape.unload_landblock(lbid);

                    if (lbid == landblockID)
                        centerBlock = r_landblock;

                    MainWindow.Status.WriteLine($"Loaded {lbid:X8} in {timer.Elapsed.TotalMilliseconds}ms");

                    //Landblocks.Add(lbid, new R_Landblock(landblock));
                }
            }

            Buffer.BuildBuffers();

            Camera.InitLandblock(centerBlock);
            GameView.ViewMode = ViewMode.World;

            FreeResources();
        }

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

public async Task<int> ExecuteAsync(
            string workingDirectory,
            string fileName,
            string arguments,
            IDictionary<string, string> environment,
            bool requireExitCodeZero,
            Encoding outputEncoding,
            bool killProcessOnCancel,
            Channel<string> redirectStandardIn,
            bool inheritConsoleHandler,
            bool keepStandardInOpen,
            bool highPriorityProcess,
            CancellationToken cancellationToken)
        {
            ArgUtil.Null(_proc, nameof(_proc));
            ArgUtil.NotNullOrEmpty(fileName, nameof(fileName));

            Trace.Info("Starting process:");
            Trace.Info($"  File name: '{fileName}'");
            Trace.Info($"  Arguments: '{arguments}'");
            Trace.Info($"  Working directory: '{workingDirectory}'");
            Trace.Info($"  Require exit code zero: '{requireExitCodeZero}'");
            Trace.Info($"  Encoding web name: {outputEncoding?.WebName} ; code page: '{outputEncoding?.CodePage}'");
            Trace.Info($"  Force kill process on cancellation: '{killProcessOnCancel}'");
            Trace.Info($"  Redirected STDIN: '{redirectStandardIn != null}'");
            Trace.Info($"  Persist current code page: '{inheritConsoleHandler}'");
            Trace.Info($"  Keep redirected STDIN open: '{keepStandardInOpen}'");
            Trace.Info($"  High priority process: '{highPriorityProcess}'");

            _proc = new Process();
            _proc.StartInfo.FileName = fileName;
            _proc.StartInfo.Arguments = arguments;
            _proc.StartInfo.WorkingDirectory = workingDirectory;
            _proc.StartInfo.UseShellExecute = false;
            _proc.StartInfo.CreateNoWindow = !inheritConsoleHandler;
            _proc.StartInfo.RedirectStandardInput = true;
            _proc.StartInfo.RedirectStandardError = true;
            _proc.StartInfo.RedirectStandardOutput = true;

            // Ensure we process STDERR even the process exit event happen before we start read STDERR stream. 
            if (_proc.StartInfo.RedirectStandardError)
            {
                Interlocked.Increment(ref _asyncStreamReaderCount);
            }

            // Ensure we process STDOUT even the process exit event happen before we start read STDOUT stream.
            if (_proc.StartInfo.RedirectStandardOutput)
            {
                Interlocked.Increment(ref _asyncStreamReaderCount);
            }

#if OS_WINDOWS
            // If StandardErrorEncoding or StandardOutputEncoding is not specified the on the
            // ProcessStartInfo object, then .NET PInvokes to resolve the default console output
            // code page:
            //      [DllImport("api-ms-win-core-console-l1-1-0.dll", SetLastError = true)]
            //      public extern static uint GetConsoleOutputCP();
            StringUtil.EnsureRegisterEncodings();
#endif
            if (outputEncoding != null)
            {
                _proc.StartInfo.StandardErrorEncoding = outputEncoding;
                _proc.StartInfo.StandardOutputEncoding = outputEncoding;
            }

            // Copy the environment variables.
            if (environment != null && environment.Count > 0)
            {
                foreach (KeyValuePair<string, string> kvp in environment)
                {
                    _proc.StartInfo.Environment[kvp.Key] = kvp.Value;
                }
            }

            // Indicate GitHub Actions process.
            _proc.StartInfo.Environment["GITHUB_ACTIONS"] = "true";

            // Set CI=true when no one else already set it.
            // CI=true is common set in most CI provider in GitHub
            if (!_proc.StartInfo.Environment.ContainsKey("CI") &&
                Environment.GetEnvironmentVariable("CI") == null)
            {
                _proc.StartInfo.Environment["CI"] = "true";
            }

            // Hook up the events.
            _proc.EnableRaisingEvents = true;
            _proc.Exited += ProcessExitedHandler;

            // Start the process.
            _stopWatch = Stopwatch.StartNew();
            _proc.Start();

            // Decrease invoked process priority, in platform specifc way, relative to parent
            if (!highPriorityProcess)
            {
                DecreaseProcessPriority(_proc);
            }

            // Start the standard error notifications, if appropriate.
            if (_proc.StartInfo.RedirectStandardError)
            {
                StartReadStream(_proc.StandardError, _errorData);
            }

            // Start the standard output notifications, if appropriate.
            if (_proc.StartInfo.RedirectStandardOutput)
            {
                StartReadStream(_proc.StandardOutput, _outputData);
            }

            if (_proc.StartInfo.RedirectStandardInput)
            {
                if (redirectStandardIn != null)
                {
                    StartWriteStream(redirectStandardIn, _proc.StandardInput, keepStandardInOpen);
                }
                else
                {
                    // Close the input stream. This is done to prevent commands from blocking the build waiting for input from the user.
                    _proc.StandardInput.Close();
                }
            }

            var cancellationFinished = new TaskCompletionSource<bool>();
            using (var registration = cancellationToken.Register(async () =>
            {
                await CancelAndKillProcessTree(killProcessOnCancel);
                cancellationFinished.TrySetResult(true);
            }))
            {
                Trace.Info($"Process started with process id {_proc.Id}, waiting for process exit.");
                while (true)
                {
                    Task outputSignal = _outputProcessEvent.WaitAsync();
                    var signaled = await Task.WhenAny(outputSignal, _processExitedCompletionSource.Task);

                    if (signaled == outputSignal)
                    {
                        ProcessOutput();
                    }
                    else
                    {
                        _stopWatch.Stop();
                        break;
                    }
                }

                // Just in case there was some pending output when the process shut down go ahead and check the
                // data buffers one last time before returning
                ProcessOutput();

                if (cancellationToken.IsCancellationRequested)
                {
                    // Ensure cancellation also finish on the cancellationToken.Register thread.
                    await cancellationFinished.Task;
                    Trace.Info($"Process Cancellation finished.");
                }

                Trace.Info($"Finished process {_proc.Id} with exit code {_proc.ExitCode}, and elapsed time {_stopWatch.Elapsed}.");
            }

            cancellationToken.ThrowIfCancellationRequested();

            // Wait for process to finish.
            if (_proc.ExitCode != 0 && requireExitCodeZero)
            {
                throw new ProcessExitCodeException(exitCode: _proc.ExitCode, fileName: fileName, arguments: arguments);
            }

            return _proc.ExitCode;
        }

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

public async Task<IssuedToken> GetTokenAsync(
            IssuedToken failedToken,
            CancellationToken cancellationToken)
        {
            IssuedToken currentToken = this.CurrentToken;
            VssTraceActivity traceActivity = VssTraceActivity.Current;
            Stopwatch aadAuthTokenTimer = Stopwatch.StartNew();
            try
            {
                VssHttpEventSource.Log.AuthenticationStart(traceActivity);

                if (currentToken != null)
                {
                    VssHttpEventSource.Log.IssuedTokenRetrievedFromCache(traceActivity, this, currentToken);
                    return currentToken;
                }
                else
                {
                    GetTokenOperation operation = null;
                    try
                    {
                        GetTokenOperation operationInProgress;
                        operation = CreateOperation(traceActivity, failedToken, cancellationToken, out operationInProgress);
                        if (operationInProgress == null)
                        {
                            return await operation.GetTokenAsync(traceActivity).ConfigureAwait(false);
                        }
                        else
                        {
                            return await operationInProgress.WaitForTokenAsync(traceActivity, cancellationToken).ConfigureAwait(false);
                        }
                    }
                    finally
                    {
                        lock (m_thisLock)
                        {
                            m_operations.Remove(operation);
                        }

                        operation?.Dispose();
                    }
                }
            }
            finally
            {
                VssHttpEventSource.Log.AuthenticationStop(traceActivity);

                aadAuthTokenTimer.Stop();
                TimeSpan getTokenTime = aadAuthTokenTimer.Elapsed;

                if(getTokenTime.TotalSeconds >= c_slowTokenAcquisitionTimeInSeconds)
                {
                    // It may seem strange to preplaced the string value of TotalSeconds into this method, but testing
                    // showed that ETW is persnickety when you register a method in an EventSource that doesn't
                    // use strings or integers as its parameters. It is easier to simply give the method a string
                    // than figure out to get ETW to reliably accept a double or TimeSpan.
                    VssHttpEventSource.Log.AuthorizationDelayed(getTokenTime.TotalSeconds.ToString());
                }
            }
        }

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

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task TestCancel()
        {
            const int SecondsToRun = 20;
            using (TestHostContext hc = new TestHostContext(this))
            using (var tokenSource = new CancellationTokenSource())
            {
                Tracing trace = hc.GetTrace();
                var processInvoker = new ProcessInvokerWrapper();
                processInvoker.Initialize(hc);
                Stopwatch watch = Stopwatch.StartNew();
                Task execTask;
#if OS_WINDOWS
                execTask = processInvoker.ExecuteAsync("", "cmd.exe", $"/c \"choice /T {SecondsToRun} /D y\"", null, tokenSource.Token);
#else
                execTask = processInvoker.ExecuteAsync("", "bash", $"-c \"sleep {SecondsToRun}s\"", null, tokenSource.Token);
#endif
                await Task.Delay(500);
                tokenSource.Cancel();
                try
                {
                    await execTask;
                }
                catch (OperationCanceledException)
                {
                    trace.Info("Get expected OperationCanceledException.");
                }

                replacedert.True(execTask.IsCompleted);
                replacedert.True(!execTask.IsFaulted);
                replacedert.True(execTask.IsCanceled);
                watch.Stop();
                long elapsedSeconds = watch.ElapsedMilliseconds / 1000;

#if ARM
                // if cancellation fails, then execution time is more than 15 seconds
                // longer time to compensate for a slower ARM environment (e.g. Raspberry Pi)
                long expectedSeconds = (SecondsToRun * 3) / 4;
#else
                // if cancellation fails, then execution time is more than 10 seconds
                long expectedSeconds = SecondsToRun / 2;
#endif

                replacedert.True(elapsedSeconds <= expectedSeconds, $"cancellation failed, because task took too long to run. {elapsedSeconds}");
            }
        }

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 : ParallelTests.cs
License : MIT License
Project Creator : adamecr

[TestMethod]
        public void ParallelTest()
        {
            TestContext.WriteLine("");
            var stopWatch = System.Diagnostics.Stopwatch.StartNew();

            var parallel = Enumerable.Range(10, 17)
                 .AsParallel()
                 .AsOrdered()
                 .Select(n =>
                {
                    var startInner = DateTime.Now;
                    var ctx = DmnExecutionContextFactory.CreateExecutionContext(def);
                    ctx.WithInputParameter("numin", -1 * n);
                    ctx.WithInputParameter("str", "2018-01-" + n);
                    ctx.WithInputParameter("dt", DateTime.ParseExact("2019-01-01 01:01", "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture));
                    var result = ctx.Reset().ExecuteDecision("sfeel");
                    var endInner = DateTime.Now;
                    var msInner = (endInner - startInner).Milliseconds;
                    TestContext.WriteLine($"Done for n={n} - execution time: {msInner}ms, start: {startInner:HH:mm:ss.ffff}, end: {endInner:HH:mm:ss.ffff}");
                    return result;
                })
                 .ToArray();

            stopWatch.Stop();
            var ms = stopWatch.ElapsedMilliseconds;
            TestContext.WriteLine($"All done - Total execution time: {ms}ms");

            foreach (var result in parallel)
            {
                result.Should().NotBeNull();
                result.IsSingleResult.Should().Be(true);
                result.SingleResult.Should().NotBeNull();
                result.SingleResult.Should().HaveCount(3);

                var outNumInOut = result.SingleResult[2];
                outNumInOut.Should().NotBeNull();
                outNumInOut.Name.Should().Be("numinout");
                outNumInOut.Type.Should().Be(typeof(int));
                var numInOut = (int)outNumInOut.Value;

                var outO = result.SingleResult[0];
                outO.Should().NotBeNull();
                outO.Name.Should().Be("o");
                outO.Value.Should().Be("2018-01" + numInOut).And.BeOfType<string>();
                outO.Type.Should().Be(typeof(string));

                var outNumOut = result.SingleResult[1];
                outNumOut.Should().NotBeNull();
                outNumOut.Name.Should().Be("numout");
                outNumOut.Value.Should().Be(4 * numInOut).And.BeOfType<int>();
                outNumOut.Type.Should().Be(typeof(int));
            }
        }

19 View Source File : ActionTarget`1.cs
License : Apache License 2.0
Project Creator : adamralph

private async Task RunAsync(TInput input, bool dryRun, Output output, Func<Exception, bool> messageOnly, IReadOnlyCollection<Target> dependencyPath)
        {
            var id = Guid.NewGuid();

            await output.Starting(this, input, id, dependencyPath).Tax();

            TimeSpan? duration = null;

            if (!dryRun)
            {
                try
                {
                    var stopWatch = Stopwatch.StartNew();

                    try
                    {
                        await this.action(input).Tax();
                    }
                    finally
                    {
                        duration = stopWatch.Elapsed;
                    }
                }
                catch (Exception ex)
                {
                    if (!messageOnly(ex))
                    {
                        await output.Error(this, input, ex).Tax();
                    }

                    await output.Failed(this, input, ex, duration, id, dependencyPath).Tax();

                    throw new TargetFailedException($"Target '{this.Name}' failed with input '{input}'.", ex);
                }
            }

            await output.Succeeded(this, input, duration, id, dependencyPath).Tax();
        }

19 View Source File : ActionTarget.cs
License : Apache License 2.0
Project Creator : adamralph

public override async Task RunAsync(bool dryRun, bool parallel, Output output, Func<Exception, bool> messageOnly, IReadOnlyCollection<Target> dependencyPath)
        {
            await output.BeginGroup(this).Tax();
            await output.Starting(this, dependencyPath).Tax();

            TimeSpan? duration = null;

            if (!dryRun)
            {
                try
                {
                    var stopWatch = Stopwatch.StartNew();

                    try
                    {
                        await this.action().Tax();
                    }
                    finally
                    {
                        duration = stopWatch.Elapsed;
                    }
                }
                catch (Exception ex)
                {
                    if (!messageOnly(ex))
                    {
                        await output.Error(this, ex).Tax();
                    }

                    await output.Failed(this, ex, duration, dependencyPath).Tax();
                    await output.EndGroup().Tax();

                    throw new TargetFailedException($"Target '{this.Name}' failed.", ex);
                }
            }

            await output.Succeeded(this, dependencyPath, duration).Tax();
            await output.EndGroup().Tax();
        }

19 View Source File : Form1.cs
License : The Unlicense
Project Creator : ADeltaX

private void T_Tick(object sender, EventArgs e)
        {
            this.Invoke(new Action(() =>
            {
                this.Text = "Creating controls....";
                Stopwatch sp = Stopwatch.StartNew();
                Controls.Clear();
                for (int i = 0; i < columnGrid; i++)
                {
                    for (int j = 0; j < columnGrid + 1; j++) // 100 controls instead of 99
                    {
                        Control b = new Control();
                        b.Height = size;
                        b.Width = size;
                        b.Padding = Padding.Empty;
                        b.Margin = Padding.Empty;
                        //Random may slow down a bit, but it's for visual
                        //To test controls generation speed properly, please set a fixed color.
                        b.BackColor = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
                        b.Location = new Point(i * size, j * size);
                        Controls.Add(b);
                    }
                }

                label1.Visible = false;
                sp.Stop();
                this.Text = "Controls created in: " + sp.Elapsed.ToString("mm\\:ss\\.fff");
            }));
            t.Stop();
        }

19 View Source File : ContentMap.cs
License : MIT License
Project Creator : Adoxio

public void Using(ContentMapLockType lockType, Action action,
			[CallerMemberName] string memberName = "",
			[CallerFilePath] string sourceFilePath = "",
			[CallerLineNumber] int sourceLineNumber = 0)
		{
			var timer = Stopwatch.StartNew();
			var contentMapCallId = Guid.NewGuid();

			CmsEventSource.Log.ContentMapLockStatus(lockType, "Requested", timer.ElapsedMilliseconds);
			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("ContentMap[{0}]: LockType - {1}, Requested - {2}", contentMapCallId, lockType, timer.ElapsedMilliseconds),
				memberName, sourceFilePath, sourceLineNumber);

			if (lockType == ContentMapLockType.Read && !_lock.TryEnterReadLock(LockTimeout))
			{
				TraceLock("Using", _lock);
				CmsEventSource.Log.ContentMapLockTimeout(lockType, _lock);
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("ContentMap[{0}]: Failed to acquire read lock on content map. LockType - {1}", contentMapCallId, lockType),
					memberName, sourceFilePath, sourceLineNumber);

				throw new TimeoutException("Failed to acquire read lock on content map.");
			}

			if (lockType == ContentMapLockType.Write && !_lock.TryEnterWriteLock(LockTimeout))
			{
				TraceLock("Using", _lock);
				CmsEventSource.Log.ContentMapLockTimeout(lockType, _lock);
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("ContentMap[{0}]: A write lock couldn't be acquired on the content map. LockType - {1}", contentMapCallId, lockType),
					memberName, sourceFilePath, sourceLineNumber);

				throw new TimeoutException("A write lock couldn't be acquired on the content map.");
			}

			try
			{
				CmsEventSource.Log.ContentMapLockStatus(lockType, "Acquired", timer.ElapsedMilliseconds);
				ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("ContentMap[{0}]: LockType - {1}, Acquired - {2}", contentMapCallId, lockType, timer.ElapsedMilliseconds),
					memberName, sourceFilePath, sourceLineNumber);
				action();
			}
			finally
			{
				if (lockType == ContentMapLockType.Read) _lock.ExitReadLock();
				if (lockType == ContentMapLockType.Write) _lock.ExitWriteLock();

				timer.Stop();

				CmsEventSource.Log.ContentMapLockStatus(lockType, "Released", timer.ElapsedMilliseconds);
				ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("ContentMap[{0}]: LockType - {1}, Released - {2}", contentMapCallId, lockType, timer.ElapsedMilliseconds),
					memberName, sourceFilePath, sourceLineNumber);
			}
		}

19 View Source File : ContentMapProvider.cs
License : MIT License
Project Creator : Adoxio

private ContentMap GetContentMap(CrmDbContext context)
		{
			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("LockTimeout={0}", this.LockTimeout));

			var sw = Stopwatch.StartNew();

			var solution = this.SolutionDefinitionProvider.GetSolution();
			var parameters = this.SolutionDefinitionProvider.GetQueryParameters();
			var map = new ContentMap(solution) { LockTimeout = this.LockTimeout.GetValueOrDefault(TimeSpan.FromMinutes(1)) };
			var enreplacedies = this.GetEnreplacedies(context, map.Solution, parameters).ToList();

			map.Using(ContentMapLockType.Write, () => this.BuildContentMap(map, enreplacedies));

			sw.Stop();

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Duration: {0} ms", sw.ElapsedMilliseconds));

			return map;
		}

19 View Source File : ContentMapProvider.cs
License : MIT License
Project Creator : Adoxio

protected virtual void BuildContentMap(ContentMap map, IEnumerable<Enreplacedy> enreplacedies)
		{
			var sw = Stopwatch.StartNew();

			map.AddRange(enreplacedies);

			ApplyBaseSolutionVersionToWebsite(map);

			sw.Stop();

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Duration: {0} ms", sw.ElapsedMilliseconds));
		}

19 View Source File : CmsCrmEntitySecurityProvider.cs
License : MIT License
Project Creator : Adoxio

public override bool Tryreplacedert(OrganizationServiceContext context, Enreplacedy enreplacedy, CrmEnreplacedyRight right, CrmEnreplacedyCacheDependencyTrace dependencies)
			{
				if (enreplacedy != null)
				{
					ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format(
						"right={0}, logicalName={1}, id={2}",
						right, EnreplacedyNamePrivacy.GetEnreplacedyName(enreplacedy.LogicalName),
						enreplacedy.Id));
				}
				else
				{
					ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("right={0}", right));
				}

				var timer = Stopwatch.StartNew();

				var result = InnerTryreplacedert(context, enreplacedy, right, dependencies);

				timer.Stop();

				ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("result={0}, duration={1} ms", result, timer.ElapsedMilliseconds));

				return result;
			}

19 View Source File : CrmEntityIndexBuilder.cs
License : MIT License
Project Creator : Adoxio

public void BuildIndex()
		{
			var timer = Stopwatch.StartNew();

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Start");

			var indexers = _index.GetIndexers();

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Retrieving index doreplacedents");

			var enreplacedyIndexDoreplacedents = indexers.SelectMany(indexer => indexer.GetDoreplacedents());

			UsingWriter(MethodBase.GetCurrentMethod().Name, true, true, writer =>
			{
				foreach (var enreplacedyIndexDoreplacedent in enreplacedyIndexDoreplacedents)
				{
					writer.AddDoreplacedent(enreplacedyIndexDoreplacedent.Doreplacedent, enreplacedyIndexDoreplacedent.replacedyzer);
				}
			});

			timer.Stop();

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("End. Elapsed time: {0}", timer.ElapsedMilliseconds));
		}

19 View Source File : CrmEntityIndexBuilder.cs
License : MIT License
Project Creator : Adoxio

public void UpdateCmsEnreplacedyTree(string enreplacedyLogicalName, Guid rootEnreplacedyId, int? lcid = null)
		{
			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Begin updating Cms Enreplacedy Tree for logical name: {0}, rootEnreplacedyId: {1}", enreplacedyLogicalName, rootEnreplacedyId));
			var timer = Stopwatch.StartNew();

			if (enreplacedyLogicalName == "adx_webpage")
			{
				IContentMapProvider contentMapProvider = AdxstudioCrmConfigurationManager.CreateContentMapProvider();
				Guid[] descendantLocalizedWebPagesGuids = CmsIndexHelper.GetDescendantLocalizedWebpagesForWebpage(contentMapProvider, rootEnreplacedyId, lcid).ToArray();
				Guid[] descendantRootWebPagesGuids = CmsIndexHelper.GetDescendantRootWebpagesForWebpage(contentMapProvider, rootEnreplacedyId).ToArray();

				// -------------------- WEB PAGES ------------------------------
				if (descendantLocalizedWebPagesGuids.Any())
				{
					var localizedWebPagesUnderTargetWebPageFilter = new Fetch.Filter
					{
						Type = Microsoft.Xrm.Sdk.Query.LogicalOperator.Or,
						Conditions = new List<Fetch.Condition>()
						{
							new Fetch.Condition
							{
								Attribute = "adx_webpageid",
								Operator = Microsoft.Xrm.Sdk.Query.ConditionOperator.In,
								Values = descendantLocalizedWebPagesGuids.Cast<object>().ToList()
							},
						}
					};

					var webPageIndexers = _index.GetIndexers("adx_webpage", filters: new List<Fetch.Filter> { localizedWebPagesUnderTargetWebPageFilter });

					UpdateWithIndexers("adx_webpage", webPageIndexers);
				}

				// -------------------- FORUMS ------------------------------
				if (descendantRootWebPagesGuids.Any())
				{
					var rootWebPagesUnderTargetWebPageFilter = new Fetch.Filter
					{
						Type = Microsoft.Xrm.Sdk.Query.LogicalOperator.Or,
						Conditions = new List<Fetch.Condition>()
						{
							new Fetch.Condition
							{
								Attribute = "adx_webpageid",
								Operator = Microsoft.Xrm.Sdk.Query.ConditionOperator.In,
								Values = descendantRootWebPagesGuids.Cast<object>().ToList()
							},
						}
					};

					var forumBlogToParentPageLink = new Fetch.Link
					{
						Name = "adx_webpage",
						FromAttribute = "adx_webpageid",
						ToAttribute = "adx_parentpageid",
						Filters = new List<Fetch.Filter>()
						{
							rootWebPagesUnderTargetWebPageFilter
						}
					};

					Fetch.Link languageFilter = null;

					if (lcid.HasValue)
					{
						languageFilter = new Fetch.Link
						{
							Name = "adx_websitelanguage",
							FromAttribute = "adx_websitelanguageid",
							ToAttribute = "adx_websitelanguageid",
							Type = Microsoft.Xrm.Sdk.Query.JoinOperator.Inner,
							Alias = "websitelangforupdatefilter",
							Links = new List<Fetch.Link>()
							{
								new Fetch.Link
								{
									Name = "adx_portallanguage",
									FromAttribute = "adx_portallanguageid",
									ToAttribute = "adx_portallanguageid",
									Type = Microsoft.Xrm.Sdk.Query.JoinOperator.Inner,
									Alias = "portallangforupdatefilter",
									Filters = new List<Fetch.Filter>()
									{
										new Fetch.Filter
										{
											Type = Microsoft.Xrm.Sdk.Query.LogicalOperator.And,
											Conditions = new List<Fetch.Condition>()
											{
												new Fetch.Condition
												{
													Attribute = "adx_lcid",
													Operator = Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal,
													Value = lcid.Value
												}
											}
										}
									}
								}
							}
						};
					}

					var forumBlogLinks = new List<Fetch.Link>() { forumBlogToParentPageLink };
					if (languageFilter != null)
					{
						forumBlogLinks.Add(languageFilter);
					}

					var forumIndexers = _index.GetIndexers("adx_communityforum", links: forumBlogLinks);
					UpdateWithIndexers("adx_communityforum", forumIndexers);

					var forumThreadForumLinks = new List<Fetch.Link>() { forumBlogToParentPageLink };
					if (languageFilter != null)
					{
						forumThreadForumLinks.Add(languageFilter);
					}

					var forumThreadToParentPageLink = new Fetch.Link
					{
						Name = "adx_communityforum",
						FromAttribute = "adx_communityforumid",
						ToAttribute = "adx_forumid",
						Links = forumThreadForumLinks
					};

					var forumThreadIndexers = _index.GetIndexers("adx_communityforumthread",
						links: new List<Fetch.Link>() { forumThreadToParentPageLink });
					UpdateWithIndexers("adx_communityforumthread", forumThreadIndexers);

					var forumPostToParentPageLink = new Fetch.Link
					{
						Name = "adx_communityforumthread",
						FromAttribute = "adx_communityforumthreadid",
						ToAttribute = "adx_forumthreadid",
						Alias = "adx_communityforumpost_communityforumthread",
						Links = new List<Fetch.Link>()
						{
							forumThreadToParentPageLink
						}
					};

					var forumPostIndexers = _index.GetIndexers("adx_communityforumpost",
						links: new List<Fetch.Link>() { forumPostToParentPageLink });
					UpdateWithIndexers("adx_communityforumpost", forumPostIndexers);

					// -------------------- BLOGS ------------------------------
					var blogIndexers = _index.GetIndexers("adx_blog", links: forumBlogLinks);
					UpdateWithIndexers("adx_blog", blogIndexers);

					var blogPostBlogLinks = new List<Fetch.Link>() { forumBlogToParentPageLink };
					if (languageFilter != null)
					{
						blogPostBlogLinks.Add(languageFilter);
					}

					var blogPostParentPageLink = new Fetch.Link
					{
						Name = "adx_blog",
						FromAttribute = "adx_blogid",
						ToAttribute = "adx_blogid",
						Alias = "adx_blog_blogpost",
						Links = blogPostBlogLinks
					};

					var blogPostIndexers = _index.GetIndexers("adx_blogpost", links: new List<Fetch.Link> { blogPostParentPageLink });
					UpdateWithIndexers("adx_blogpost", blogPostIndexers);
				}
			}
			else if (enreplacedyLogicalName == "adx_communityforum")
			{
				UpdateEnreplacedy("adx_communityforum", rootEnreplacedyId);

				var inForumFilterForThread = new Fetch.Filter
				{
					Type = Microsoft.Xrm.Sdk.Query.LogicalOperator.And,
					Conditions = new List<Fetch.Condition>()
					{
						new Fetch.Condition
						{
							Attribute = "adx_forumid",
							Operator = Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal,
							Value = rootEnreplacedyId
						}
					}
				};

				var forumThreadIndexers = _index.GetIndexers("adx_communityforumthread", filters: new List<Fetch.Filter> { inForumFilterForThread });
				UpdateWithIndexers("adx_communityforumthread", forumThreadIndexers);

				var inForumFilterForPost = new Fetch.Link
				{
					Name = "adx_communityforumthread",
					FromAttribute = "adx_communityforumthreadid",
					ToAttribute = "adx_forumthreadid",
					Alias = "adx_communityforumpost_communityforumthread",
					Filters = new List<Fetch.Filter>()
					{
					   inForumFilterForThread
					}
				};

				var forumPostIndexers = _index.GetIndexers("adx_communityforumpost", links: new List<Fetch.Link> { inForumFilterForPost });
				UpdateWithIndexers("adx_communityforumpost", forumPostIndexers);
			}
			else if (enreplacedyLogicalName == "adx_ideaforum")
			{
				UpdateEnreplacedy("adx_ideaforum", rootEnreplacedyId);

				var inIdeaForumFilter = new Fetch.Filter
				{
					Type = Microsoft.Xrm.Sdk.Query.LogicalOperator.And,
					Conditions = new List<Fetch.Condition>()
					{
						new Fetch.Condition
						{
							Attribute = "adx_ideaforumid",
							Operator = Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal,
							Value = rootEnreplacedyId
						}
					}
				};

				var ideaIndexers = _index.GetIndexers("adx_idea", filters: new List<Fetch.Filter> { inIdeaForumFilter });
				UpdateWithIndexers("adx_idea", ideaIndexers);
			}

			timer.Stop();
			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Cms Enreplacedy Tree updated for logical name: {0}, rootEnreplacedyId: {1}, timespan: {2}", enreplacedyLogicalName, rootEnreplacedyId, timer.ElapsedMilliseconds));
		}

19 View Source File : OrganizationServiceCache.cs
License : MIT License
Project Creator : Adoxio

private TResult LookupAndInsert<TRequest, TResponse, TResult>(TRequest query, Func<TRequest, TResponse> execute, Func<TResponse, TResult> selector, string selectorCacheKey, bool allowStaleData = false)
		{
			int cacheMissedMetricValue;

			string queryText;

			var stopwatch = Stopwatch.StartNew();
			var cacheKey = GetCacheKey(query, selectorCacheKey, out queryText);
			var response = GetCachedResult(query, execute, selector, cacheKey, out cacheMissedMetricValue);

			var cacheItemDetail = Cache.GetCacheItemDetail(cacheKey, CacheRegionName);

			if (cacheItemDetail != null)
			{
				// If the item is marked dirty, fetch the latest changes from CRM.
				if (cacheItemDetail.CacheItemStatus == CacheItemStatus.Dirty)
				{
					// Set the cache item status to BeingProcessed, before fetching changes from CRM.
					if (cacheItemDetail.TrySetCacheItemStatus(CacheItemStatus.BeingProcessed))
					{
						using (sessionIdLock.Lock(cacheItemDetail.SessionId))
						{
							// Fetch the latest chagnes from CRM and update the cache item.
							cacheMissedMetricValue = 1;
							response = InnerExecute(query, execute, selector);
							Insert(cacheKey, query, response);
						}

						// Set the cache item status to update after it is updated in the cache.
						// Since inserting the latest data in the cache, would perform a cache.Set operation on the actual cache key, it would refresh the cacheItemDetail and cacheItemTelemetry items in the cache.
						// So we can skip the step to update the CacheItemStatus, since it is already updated to current.
					}
					else
					{
						// If thread was not able to flip the CacheItemStatus flag, it will access the stale data. Update the stale access count for the given key.
						ADXTrace.Instance.TraceInfo(TraceCategory.CacheInfra, string.Format("Cache hit with stale Data. Could not flip CacheItemStatus, CacheKey={0}, IsStaleAllowed={1}", cacheKey, cacheItemDetail?.IsStaleDataAllowed == true));
						Cache.IncrementStaleAccessCount(cacheKey, CacheRegionName);
					}
				}
				// The below logic is handle those scenarios where the reader is the same thread which marked the cache item as dirty.
				// In such case, we would not want the reader to return the stale data.
				// Ideally it should be this reader that should update the cache item. But since there is no way to ensure that, we should keep it blocked until the data in the cache is refreshed.
				// To identify that this is the same thread which marked the cache item dirty, we are using session id (which is stored in CacheItemDetail)
				else if (cacheItemDetail.CacheItemStatus == CacheItemStatus.BeingProcessed
					&& !string.IsNullOrEmpty(cacheItemDetail.SessionId)
					&& cacheItemDetail.SessionId.Equals(GetSessionId()))
				{
					using (sessionIdLock.Lock(cacheItemDetail.SessionId))
					{
						// Retrieve the latest response from cache.
						ADXTrace.Instance.TraceInfo(TraceCategory.CacheInfra, string.Format("Cache hit - Session Lock, CacheKey={0}, IsStaleAllowed={1}", cacheKey, cacheItemDetail?.IsStaleDataAllowed == true));
						response = GetCachedResult(query, execute, selector, cacheKey, out cacheMissedMetricValue);
					}
				}
				else if (cacheItemDetail.CacheItemStatus == CacheItemStatus.BeingProcessed)
				{
					// Update the stale access account for the given cache key.
					ADXTrace.Instance.TraceInfo(TraceCategory.CacheInfra, string.Format("Cache hit with stale Data, CacheKey={0}, IsStaleAllowed={1}", cacheKey, cacheItemDetail?.IsStaleDataAllowed == true));
					Cache.IncrementStaleAccessCount(cacheKey, CacheRegionName);
				}

				// Check if we want to allow stale data for this request or not.
				if (allowStaleData)
				{
					// Retrieve the latest cacheItemDetail from the cache, in case it is refresed
					cacheItemDetail = Cache.GetCacheItemDetail(cacheKey, CacheRegionName);

					if (cacheItemDetail != null)
					{
						cacheItemDetail.IsStaleDataAllowed = true;
					}
				}
			}

			stopwatch.Stop();
			MdmMetrics.CacheMissedMetric.LogValue(cacheMissedMetricValue);

			if (cacheMissedMetricValue == 0)
			{
				Cache.IncrementAccessCount(cacheKey, CacheRegionName);

				var request = query as OrganizationRequest;

				if (request != null)
				{
					ServicesEventSource.Log.OrganizationRequest(request, stopwatch.ElapsedMilliseconds, true);
				}
			}
			else
			{
				// HttpContext.Current is null in case of call out of request
				var isAuthenticated = HttpContext.Current != null && HttpContext.Current.Request.IsAuthenticated;
				ADXTrace.Instance.TraceInfo(TraceCategory.CacheInfra, string.Format("Cache miss, Query={0}, IsAuthenticated={1}, IsStaleAllowed={2}", queryText, isAuthenticated, cacheItemDetail?.IsStaleDataAllowed == true));
			}

			return this.ReturnMode == OrganizationServiceCacheReturnMode.Cloned ? this.InternalCloneResponse(response) : response;
		}

19 View Source File : ApplicationCachingCrmEntitySecurityProvider.cs
License : MIT License
Project Creator : Adoxio

public override bool Tryreplacedert(OrganizationServiceContext context, Enreplacedy enreplacedy, CrmEnreplacedyRight right, CrmEnreplacedyCacheDependencyTrace dependencies)
		{
			var info = CacheInfoFactory.GetCacheInfo(context, enreplacedy, right);

			if (!info.IsCacheable)
			{
				return UnderlyingProvider.Tryreplacedert(context, enreplacedy, right, dependencies);
			}

			Stopwatch stopwatch = null;

			return ObjectCacheManager.Get(info.Key,
				cache =>
				{
					stopwatch = Stopwatch.StartNew();

					var value = UnderlyingProvider.Tryreplacedert(context, enreplacedy, right, dependencies);

					stopwatch.Stop();

					return value;
				},
				(cache, value) =>
				{
					if (dependencies.IsCacheable)
					{
						cache.Insert(info.Key, value, dependencies);

						if (stopwatch != null)
						{
							cache.AddCacheItemTelemetry(info.Key, new CacheItemTelemetry { Duration = stopwatch.Elapsed });
						}
					}
				});
		}

See More Examples