public void TestExecutionOnTime()
        {
            var tickDuration       = TimeSpan.FromMilliseconds(200);
            var timeout            = TimeSpan.FromMilliseconds(125);
            var nanoTimeout        = NanoTime.FromMilliseconds(125);
            var maxTimeout         = 2 * (tickDuration + timeout);
            var nanoMaxTimeout     = NanoTime.FromMilliseconds(maxTimeout.TotalMilliseconds);
            HashedWheelTimer timer = new HashedWheelTimer(tickDuration);
            var queue = new BlockingCollection <long>();

            var watch = new ConcurrentStopwatch();

            watch.Start();
            int scheduledTasks = 100000;

            for (int i = 0; i < scheduledTasks; i++)
            {
                var start = watch.Elapsed;
                timer.ScheduleTimeout(() =>
                {
                    queue.Add(watch.Elapsed - start);
                }, timeout);
            }

            for (int i = 0; i < scheduledTasks; i++)
            {
                long delay = queue.Take();
                Assert.True(delay >= nanoTimeout && delay < nanoMaxTimeout, i + ": Timeout + " + scheduledTasks + " delay " + delay + " must be " + timeout + " < " + maxTimeout);
            }

            timer.Stop();
        }
示例#2
0
        static void Work(int thread_num, ConcurrentStopwatch stopwatch, ref int predicted_total_ms)
        {
            var rand = new Random(thread_num);

            for (int i = 0; i < 1000; ++i)
            {
                int delay_in_ms = rand.Next(10);
                Interlocked.Add(ref predicted_total_ms, delay_in_ms);
                using (stopwatch.Measure())
                    Thread.Sleep(delay_in_ms);
            }
        }
        public void TestDelayTimeoutShouldNotLargerThanSingleTickDuration(int tickInterval, int timeout)
        {
            var  watch   = new ConcurrentStopwatch();
            var  barrier = new CountdownEvent(1);
            var  timer   = new HashedWheelTimer(interval: TimeSpan.FromMilliseconds(tickInterval));
            long elapsed = 0;

            watch.Start();
            timer.ScheduleTimeout(() =>
            {
                Interlocked.Exchange(ref elapsed, watch.Elapsed);
                barrier.Signal();
            }, TimeSpan.FromMilliseconds(timeout));

            Assert.True(barrier.Wait(tickInterval * 2 + timeout), $"Elapsed: {NanoTime.ToMilliseconds(elapsed)}, ticks interval: {tickInterval}, timeout: {timeout}.");
        }
        private void MakeTimestampsMultithreaded(object cancellationToken)
        {
            _timestamps.Clear();
            while (!((CancellationToken)cancellationToken).IsCancellationRequested)
            {
                var timestamp = ConcurrentStopwatch.GetMicroseconds();
                if (!_timestamps.TryAdd(timestamp, DateTime.Now.TimeOfDay))
                {
                    var value   = _timestamps[timestamp];
                    var indexOf = _timestamps.Keys.ToList().IndexOf(timestamp);
                    Console.WriteLine("Current timestamp count: {0}", _ids.Count);
                    Console.WriteLine("Last Id: {0}", _newId);
                    Console.WriteLine("ThreadId: {0}", Thread.CurrentThread.ManagedThreadId);
                    Console.WriteLine("ThreadId of duplicate timestamp: {0}", value);
                    Console.WriteLine("Index of existing item: {0}", indexOf);

                    throw new InvalidOperationException("Duplicate timestamp!");
                }
            }
        }
示例#5
0
        public void TestConcurrency()
        {
            var stopwatch          = new ConcurrentStopwatch();
            int predicted_total_ms = 0;
            // don't use parallel.foreach, we want context switches
            var threads = Enumerable.Range(0, 100).Select(i => new Thread(() => Work(i, stopwatch, ref predicted_total_ms))).ToArray();

            foreach (var thread in threads)
            {
                thread.Start();
            }
            foreach (var thread in threads)
            {
                thread.Join();
            }
            double delta = Math.Abs(predicted_total_ms - stopwatch.ElapsedMS.Value);

            Console.WriteLine("ConcurrentStopwatch error margin: {0:0.000}%", delta * 100 / predicted_total_ms);
            Assert.IsTrue(delta < 0.1 * predicted_total_ms);
        }
示例#6
0
        async Task BuildAsync()
        {
            if (LoggerVerbosity != LoggerVerbosity.Quiet)
            {
                Messages.Print(clear: !QtVsToolsPackage.Instance.Options.BuildDebugInformation, activate: true,
                               text: string.Format(
                                   @"== {0}: starting build...
  * Properties: {1}
  * Targets: {2}
",
                                   /*{0}*/ Path.GetFileNameWithoutExtension(UnconfiguredProject.FullPath),
                                   /*{1}*/ string.Join("", Properties
                                                       .Select(property => string.Format(@"
        {0} = {1}", /*{0}*/ property.Key, /*{1}*/ property.Value))),
                                   /*{2}*/ string.Join(";", Targets)));
            }

            var lockService = UnconfiguredProject.ProjectService.Services.ProjectLockService;

            bool ok = false;

            try {
                var timer = ConcurrentStopwatch.StartNew();
                while (timer.IsRunning)
                {
                    try {
#if VS2017
                        using (var writeAccess = await lockService.WriteLockAsync())
                            ok = await BuildProjectAsync(writeAccess);
#else
                        await lockService.WriteLockAsync(
                            async (ProjectWriteLockReleaser writeAccess) =>
                        {
                            ok = await BuildProjectAsync(writeAccess);
                        });
#endif
                        timer.Stop();
                    } catch (InvalidOperationException) {
                        if (timer.ElapsedMilliseconds >= 5000)
                        {
                            throw;
                        }
#if VS2017
                        using (var readAccess = await lockService.ReadLockAsync())
                            await readAccess.ReleaseAsync();
#else
                        await lockService.ReadLockAsync(
                            async (ProjectLockReleaser readAccess) =>
                        {
                            await readAccess.ReleaseAsync();
                        });
#endif
                    }
                }

                if (ok)
                {
                    var vcConfigs = VcProject.Configurations as IVCCollection;
                    var vcConfig  = vcConfigs.Item(ConfiguredProject.ProjectConfiguration.Name) as VCConfiguration;
                    var props     = vcConfig.Rules.Item("QtRule10_Settings") as IVCRulePropertyStorage;
                    props.SetPropertyValue("QtLastBackgroundBuild", DateTime.UtcNow.ToString("o"));
                }
            } catch (Exception e) {
                Messages.Print(string.Format("{0}: background build ERROR: {1}",
                                             Path.GetFileName(UnconfiguredProject.FullPath), e.Message));
            }

            if (LoggerVerbosity != LoggerVerbosity.Quiet)
            {
                Messages.Print(string.Format(
                                   @"
== {0}: build {1}",
                                   Path.GetFileNameWithoutExtension(UnconfiguredProject.FullPath),
                                   ok ? "successful" : "ERROR"));
            }
        }