System.TimeSpan.FromMilliseconds(double)

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

5370 Examples 7

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

public override void OnModifierMouseUp(ModifierMouseArgs e)
        {
            ModifierSurface.ReleaseMouseCapture();
            endPoint = GetPointRelativeTo(e.MousePoint, ModifierSurface);
            OnAttached();

            if (Math.Abs(startPoint.X - endPoint.X) > 10)
            {
                int i = 0;
                foreach (CustomWaterfallNumericAxis YAxis in ParentSurface.XAxes)
                {

                    YAxis.Zoom(startPoint.X + i * 2, endPoint.X + i * 2, TimeSpan.FromMilliseconds(1000));
                    i++;
                }
            }
        }

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

public T WaitForElement<T>(Func<T> getter)
        {
            var retry = Retry.WhileNull<T>(
                getter,
                TimeSpan.FromMilliseconds(BigWaitTimeout));

            if (!retry.Success)
            {
                replacedert.Fail($"Failed to get an element within a {BigWaitTimeout}ms");
            }

            return retry.Result;
        }

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

[Test]
        public void should_write_unformatted_unmanaged_struct_when_formatting_fails()
        {
            LogManager.RegisterUnmanaged<FailingUnmanagedStruct>();

            var log = LogManager.GetLogger(typeof(LogManagerTests));
            var signal = _testAppender.SetMessageCountTarget(1);

            log.Info()
               .AppendUnmanaged(new FailingUnmanagedStruct { Value = 42 })
               .Log();

            signal.Wait(TimeSpan.FromMilliseconds(100));

            var logMessage = _testAppender.LoggedMessages.Single();
            Check.That(logMessage).Equals("An error occured during formatting: Simulated failure - Arguments: Unmanaged(0x2a000000)");
        }

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

private void ZoomExtends()
        {
            _viewportManager.AnimateZoomExtents(TimeSpan.FromMilliseconds(500));
        }

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

public static TimeSpan Ms(this int ms) {
            return TimeSpan.FromMilliseconds(ms);
        }

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

[Test]
        public void should_completely_drop_log_event_when_log_event_pool_is_exhausted()
        {
            LogManager.Shutdown();
            
            BasicConfigurator.Configure(new ZeroLogBasicConfiguration
            {
                Appenders = { _testAppender },
                LogEventQueueSize = 10,
                LogEventPoolExhaustionStrategy = LogEventPoolExhaustionStrategy.DropLogMessage
            });

            var log = LogManager.GetLogger(typeof(LogManagerTests));

            var actualLogEvents = new List<ILogEvent>();
            for (var i = 0; i < 10; i++)
            {
                actualLogEvents.Add(log.Debug());
            }

            var signal = _testAppender.SetMessageCountTarget(1);

            log.Debug().Append("this is not going to happen").Log();

            Check.That(signal.Wait(TimeSpan.FromMilliseconds(100))).IsFalse();
        }

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

public override void OnModifierKeyDown(ModifierKeyArgs e)
        {
            base.OnModifierKeyDown(e);

            double factor = 0;

            if ((e.Key == Key.Add || e.Key == Key.OemPlus) && Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
            {
                // On CTRL+, Zoom In
                factor = -ZoomFraction;
            }
            if ((e.Key == Key.Subtract || e.Key == Key.OemMinus) && Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
            {
                // On CTRL-, Zoom Out
                factor = ZoomFraction;
            }

            using (ParentSurface.SuspendUpdates())
            {
                // Zoom the XAxis by the required factor
                XAxis.ZoomBy(factor, factor, TimeSpan.FromMilliseconds(500));

                // Zoom the YAxis by the required factor
                YAxis.ZoomBy(factor, factor, TimeSpan.FromMilliseconds(500));

                // Note.. can be extended for multiple YAxis XAxis, just iterate over all axes on the parent surface
            }
        }

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

static void Main(string[] args)
        {
			if (args != null && args.Length == 0) args = new[] { "?" };

			ManualResetEvent wait = new ManualResetEvent(false);
			new Thread(() => {
				Thread.CurrentThread.Join(TimeSpan.FromMilliseconds(10));

                try
                {
                    ConsoleApp app = new ConsoleApp(args, wait);
                }
                finally
                {
                    wait.Set();
                }
			}).Start();
			wait.WaitOne();
			return;
		}

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

private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
        {
            // (2): Create a DataSeries and replacedign to FastLineRenderableSeries
            _dataSeries = new XyDataSeries<double, double>();
            _random = new Random();
            lineSeries.DataSeries = _dataSeries;

            _labelProvider = new RelativeTimeLabelProvider();
            xAxis.LabelProvider = _labelProvider;
            sciChartSurface.InvalidateElement();

            // (6): We subscribe to PreviewMouseDown to set a flag to prevent scrolling calculation in (5)
            sciChartSurface.PreviewMouseDown += (s, arg) =>
            {
                // On mouse down (but not double click), freeze our last N seconds window 
                if (!_thatWasADoubleClick) _showLatestWindow = false;

                _thatWasADoubleClick = false;
            };

            // (7): Subscribe to PreviewMouseDoubleClick to re-enable the auto scrolling window
            sciChartSurface.PreviewMouseDoubleClick += (s, arg) =>
            {
                _showLatestWindow = true;
                _thatWasADoubleClick = true; // (8): Prevent contention between double click and single click event

                // Restore our last N seconds window on double click
                yAxis.AnimateVisibleRangeTo(new DoubleRange(0, 1), TimeSpan.FromMilliseconds(200));
                xAxis.AnimateVisibleRangeTo(new DoubleRange(_timeNow - _windowSize, _timeNow), TimeSpan.FromMilliseconds(200));
            };

            // (3): Create a timer to tick new data 
            var timer = new DispatcherTimer(DispatcherPriority.Render);
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += TimerOnTick;
            timer.Start();
        }

19 View Source File : PropertyTests.cs
License : MIT License
Project Creator : 71

[Fact]
        public void TestStaticProperties()
        {
            PropertyInfo randomProperty = typeof(PropertyTests)
                .GetProperty(nameof(Random), BindingFlags.Static | BindingFlags.Public);
            PropertyInfo nowProperty = typeof(DateTime)
                .GetProperty(nameof(DateTime.Now), BindingFlags.Static | BindingFlags.Public);


            DateTime.Now.ShouldNotBe(Random, tolerance: TimeSpan.FromMilliseconds(100));

            using (Redirection.Redirect(randomProperty, nowProperty))
            {
                DateTime.Now.ShouldBe(Random, tolerance: TimeSpan.FromMilliseconds(100));
            }

            DateTime.Now.ShouldNotBe(Random, tolerance: TimeSpan.FromMilliseconds(100));
        }

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

private void Slider_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (_timer != null)
            {
                _timer.Interval = TimeSpan.FromMilliseconds(Slider.Value);
            }
        }

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

private void OnExampleLoaded(object sender, RoutedEventArgs e)
        {
            if (_timerNewDataUpdate == null)
            {
                _timerNewDataUpdate = new DispatcherTimer(DispatcherPriority.Render);
                _timerNewDataUpdate.Tick += OnTimerTick;
                _timerNewDataUpdate.Interval = TimeSpan.FromMilliseconds(25);
                _timerNewDataUpdate.Start();
            }
        }

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

[Test]
        public void should_return_special_log_event_when_no_more_log_event_are_available()
        {
            var log = LogManager.GetLogger(typeof(LogManagerTests));

            var actualLogEvents = new List<ILogEvent>();
            for (var i = 0; i < 10; i++)
            {
                actualLogEvents.Add(log.Debug());
            }

            var unavailableEvent = log.Debug();

            Check.That(actualLogEvents.OfType<LogEvent>().Count()).Equals(actualLogEvents.Count);
            Check.That(unavailableEvent).IsInstanceOf<ForwardingLogEvent>();

            var signal = _testAppender.SetMessageCountTarget(actualLogEvents.Count);

            for (var i = 0; i < actualLogEvents.Count; i++)
            {
                var actualLogEvent = actualLogEvents[i];
                actualLogEvent.Append(i).Log();
            }

            signal.Wait(TimeSpan.FromMilliseconds(100));

            Check.That(log.Debug()).IsInstanceOf<LogEvent>();
        }

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

private void ZoomExtentsClick(object sender, EventArgs e)
        {
            chart0.AnimateZoomExtents(TimeSpan.FromMilliseconds(500));
            chart1.AnimateZoomExtents(TimeSpan.FromMilliseconds(500));
        }

19 View Source File : IdleBus`1.ThreadScan.cs
License : MIT License
Project Creator : 2881099

bool ThreadJoin(TimeSpan interval)
        {
            if (interval <= TimeSpan.Zero) return true;
            var milliseconds = interval.TotalMilliseconds;
            var seconds = Math.Floor(milliseconds / 1000);
            milliseconds = milliseconds - seconds * 1000;

            for (var a = 0; a < seconds; a++)
            {
                Thread.CurrentThread.Join(TimeSpan.FromSeconds(1));
                if (isdisposed) return false;
            }
            for (var a = 0; a < milliseconds; a += 200)
            {
                Thread.CurrentThread.Join(TimeSpan.FromMilliseconds(200));
                if (isdisposed) return false;
            }
            return true;
        }

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

public void WaitUntilClosed(AutomationElement element)
        {
            var result = Retry.WhileFalse(() => element.IsOffscreen, TimeSpan.FromMilliseconds(BigWaitTimeout));
            if (!result.Success)
            {
                replacedert.Fail($"Element failed to go offscreen within {BigWaitTimeout}ms");
            }
        }

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

[Test]
        public void should_not_throw_if_formatting_fails_when_using_format_string()
        {
            var log = LogManager.GetLogger(typeof(LogManagerTests));
            var signal = _testAppender.SetMessageCountTarget(1);

            var guid = Guid.NewGuid();
            log.InfoFormat("A good format: {0:X4}, A bad format: {1:lol}, Another good format: {2}", (short)-23805, guid, true);

            signal.Wait(TimeSpan.FromMilliseconds(100));

            var logMessage = _testAppender.LoggedMessages.Single();
            Check.That(logMessage).Equals("An error occured during formatting: Unknown format specifier 'lol'. - Arguments: \"A good format: {0:X4}, A bad format: {1:lol}, Another good format: {2}\", -23805, " + guid + ", True");
        }

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 : ServiceFactory.cs
License : MIT License
Project Creator : 1100100

public void Create(string route, MethodInfo serverMethodInfo, MethodInfo clientMethodInfo, List<Type> serverInterceptors, List<Type> clientInterceptors)
        {
            if (ServiceInvokers.ContainsKey(route))
                throw new DuplicateRouteException(route);
            var enableClient = ServiceProvider.GetService<ILoadBalancing>() != null;
            ServiceCircuitBreakerOptions breaker = null;
            CachingConfig cachingConfig = null;
            if (enableClient)
            {
                #region Circuit breaker
                var nonCircuitBreakerAttr = clientMethodInfo.GetCustomAttribute<NonCircuitBreakerAttribute>();
                if (nonCircuitBreakerAttr == null)
                {
                    var circuitBreakerAttr = clientMethodInfo.GetCustomAttribute<CircuitBreakerAttribute>();
                    var globalCircuitBreaker = UraganoSettings.CircuitBreakerOptions;
                    if (globalCircuitBreaker != null || circuitBreakerAttr != null)
                    {
                        breaker = new ServiceCircuitBreakerOptions();
                        if (globalCircuitBreaker != null)
                        {
                            breaker.Timeout = globalCircuitBreaker.Timeout;
                            breaker.Retry = globalCircuitBreaker.Retry;
                            breaker.ExceptionsAllowedBeforeBreaking =
                                globalCircuitBreaker.ExceptionsAllowedBeforeBreaking;
                            breaker.DurationOfBreak = globalCircuitBreaker.DurationOfBreak;
                            breaker.MaxParallelization = globalCircuitBreaker.MaxParallelization;
                            breaker.MaxQueuingActions = globalCircuitBreaker.MaxQueuingActions;
                        }

                        if (circuitBreakerAttr != null)
                        {
                            if (circuitBreakerAttr.TimeoutMilliseconds > -1)
                                breaker.Timeout = TimeSpan.FromMilliseconds(circuitBreakerAttr.TimeoutMilliseconds);
                            if (circuitBreakerAttr.Retry > -1)
                                breaker.Retry = circuitBreakerAttr.Retry;
                            if (circuitBreakerAttr.ExceptionsAllowedBeforeBreaking > -1)
                                breaker.ExceptionsAllowedBeforeBreaking =
                                    circuitBreakerAttr.ExceptionsAllowedBeforeBreaking;
                            if (circuitBreakerAttr.DurationOfBreakSeconds > -1)
                                breaker.DurationOfBreak = TimeSpan.FromSeconds(circuitBreakerAttr.DurationOfBreakSeconds);
                            if (!string.IsNullOrWhiteSpace(circuitBreakerAttr.FallbackExecuteScript))
                            {
                                breaker.HasInjection = true;
                                ScriptInjection.AddScript(route, circuitBreakerAttr.FallbackExecuteScript,
                                    circuitBreakerAttr.ScriptUsingNameSpaces);
                            }

                            if (circuitBreakerAttr.MaxParallelization > -1)
                                breaker.MaxParallelization = circuitBreakerAttr.MaxParallelization;

                            if (circuitBreakerAttr.MaxQueuingActions > -1)
                                breaker.MaxQueuingActions = circuitBreakerAttr.MaxQueuingActions;
                        }
                    }
                }
                #endregion

                #region Caching
                //Must have a method of returning a value.
                if (UraganoSettings.CachingOptions != null && clientMethodInfo.ReturnType != typeof(Task) && clientMethodInfo.GetCustomAttribute<NonCachingAttribute>() == null && clientMethodInfo.DeclaringType?.GetCustomAttribute<NonCachingAttribute>() == null)
                {
                    var attr = clientMethodInfo.GetCustomAttribute<CachingAttribute>();
                    var keyGenerator = ServiceProvider.GetRequiredService<ICachingKeyGenerator>();
                    var key = keyGenerator.GenerateKeyPlaceholder(UraganoSettings.CachingOptions.KeyPrefix, UraganoSettings.CachingOptions.ExpireSeconds, route, clientMethodInfo, attr);

                    cachingConfig = new CachingConfig(key, attr != null && !string.IsNullOrWhiteSpace(attr.Key), attr != null && attr.ExpireSeconds != -1 ? attr.ExpireSeconds : UraganoSettings.CachingOptions.ExpireSeconds);
                }
                #endregion
            }
            var serviceDescriptor = new ServiceDescriptor(route, serverMethodInfo, clientMethodInfo, serverMethodInfo == null ? null : new MethodInvoker(serverMethodInfo), serverInterceptors, clientInterceptors, breaker, cachingConfig);
            ServiceInvokers.TryAdd(route, serviceDescriptor);
        }

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

private void OnStart()
        {
            if (ScatterRenderableSeries3D.DataSeries == null)
            {
                _xyzData = new XyzDataSeries3D<double>();

                // 2. I create three series not one
                _wallZyData = new XyzDataSeries3D<double>();
                _wallXyData = new XyzDataSeries3D<double>();

                var random = new Random();

                // First load, fill with some random values                    
                for (int i = 0; i < _pointCount; i++)
                {
                    double x = random.NextDouble();
                    double y = random.NextDouble();
                    double z = random.NextDouble();

                    _xyzData.Append(x, y, z);
                    _wallZyData.Append(10, y, z);
                    _wallXyData.Append(x,y,10);
                }

                ScatterRenderableSeries3D.DataSeries = _xyzData;
                WallXyScatterRenderableSeries3D.DataSeries = _wallXyData;
                WallZyScatterRenderableSeries3D.DataSeries = _wallZyData;
            }

            if (_timer == null)
            {
                _timer = new DispatcherTimer(DispatcherPriority.Render);
                _timer.Interval = TimeSpan.FromMilliseconds(1);
                _timer.Tick += OnTimerTick;
            }

            _timer.Start();
        }

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

[Test]
        public void should_truncate_long_lines()
        {
            var log = LogManager.GetLogger(typeof(LogManagerTests));

            var signal = _testAppender.SetMessageCountTarget(1);

            var longMessage = new string('.', LogManager.OutputBufferSize + 1);
            log.Info().Append(longMessage).Log();

            signal.Wait(TimeSpan.FromMilliseconds(100));
            var message = _testAppender.LoggedMessages.Single();
            Check.That(message).IsEqualTo(new string('.', LogManager.OutputBufferSize - LogManager.Config.TruncatedMessageSuffix.Length) + LogManager.Config.TruncatedMessageSuffix);
        }

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

[Test]
        public void CancellationAbortsPromise() {
            var test = new TestDef();

            var cancel = TimeSpan.MinValue;
            var result = false;
            
            test.AddScript("m:m", async env => {
                var promise = new SimFuture<bool>(5000, env.Token);
                try {
                    result = await promise.Task;
                } catch (TaskCanceledException) {
                    cancel = env.Time;
                }
            });
            
            test.Run(async plan => {
                plan.StartServices();
                await plan.Delay(1000.Sec());
                await plan.StopServices(grace:1.Sec());
            });
            
            
            replacedert.IsFalse(result);
            replacedert.AreEqual(TimeSpan.FromMilliseconds(1000), cancel, nameof(cancel));
        }

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

public async Task DisconnectAsync()
        {
            Logger.LogTrace($"Stopping client.[{Channel.LocalAddress}]");
            foreach (var task in _resultCallbackTask.Values)
            {
                task.TrySetCanceled();
            }

            _resultCallbackTask.Clear();
            if (Channel.Open)
            {
                await Channel.CloseAsync();
                await EventLoopGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }

            Logger.LogTrace($"The client[{Channel.LocalAddress}] has stopped.");
        }

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

private void OnZoomExtents()
        {
            var range = new DoubleRange(0, 10);
            XAxis.AnimateVisibleRangeTo(range, TimeSpan.FromMilliseconds(500));
            YAxis.AnimateVisibleRangeTo(range, TimeSpan.FromMilliseconds(500));
        }

19 View Source File : StateMachines.cs
License : MIT License
Project Creator : 71

[Fact]
        public void ShouldReduceAwaitToBlockingCall()
        {
            Task<string> sleepTask = new Task<string>(() =>
            {
                Thread.Sleep(1000);
                return "hey";
            });

            AwaitExpression expression = X.Await(X.Link(sleepTask));

            DateTime before = DateTime.Now;

            Action action = Expression.Lambda<Action>(expression).Compile();

            sleepTask.Start();
            action();

            TimeSpan timeTaken = DateTime.Now - before;

            timeTaken.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromMilliseconds(1000));
        }

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

private void OnExampleLoaded(object sender, RoutedEventArgs e)
        {
            // Preload with data
            for (int i = 0; i < FifoCapacity; i++)
            {
                TimerOnElapsed(null, EventArgs.Empty);
            }

            if (_timer == null)
            {
                _timer = new DispatcherTimer(DispatcherPriority.Background);
                _timer.Interval = TimeSpan.FromMilliseconds(Interval);
                _timer.Tick += TimerOnElapsed;
                _timer.Start();
            }
        }

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

private void OnStart()
        {
            StartButton.IsChecked = true;
            PauseButton.IsChecked = false;
            ResetButton.IsChecked = false;

            if (ScatterRenderableSeries3D.DataSeries == null)
            {
                _xyzData = new XyzDataSeries3D<double>();

                // First load, fill with some random values                    
                for (int i = 0; i < _pointCount; i++)
                {
                    double x = DataManager.Instance.GetGaussianRandomNumber(50, 15);
                    double y = DataManager.Instance.GetGaussianRandomNumber(50, 15);
                    double z = DataManager.Instance.GetGaussianRandomNumber(50, 15);

                    _xyzData.Append(x, y, z);
                }

                ScatterRenderableSeries3D.DataSeries = _xyzData;
            }

            if (_timer == null)
            {
                _timer = new DispatcherTimer(DispatcherPriority.Render);
                _timer.Interval = TimeSpan.FromMilliseconds(1);
                _timer.Tick += OnTimerTick;
            }

            _timer.Start();
        }

19 View Source File : ConsoleProgressBar.cs
License : MIT License
Project Creator : a-luna

internal void ResetTimer()
        {
            Timer.Change(_animationInterval, TimeSpan.FromMilliseconds(-1));
        }

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

private void OnExampleLoaded(object sender, RoutedEventArgs e)
        {
            if (_timer == null)
            {
                _timer = new DispatcherTimer(DispatcherPriority.Render)
                {
                    Interval = TimeSpan.FromMilliseconds(Slider.Value)
                };

                _timer.Tick += TimerOnElapsed;

                _timer.Start();
            }
        }

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

void Reconnect()
        {
            int attempts = 0;
            while (attempts++ < ReconnectAttempts || ReconnectAttempts == -1)
            {
                if (Connect(-1))
                    return;

                Thread.Sleep(TimeSpan.FromMilliseconds(ReconnectWait));
            }

            throw new IOException("Could not reconnect after " + attempts + " attempts");
        }

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

void MultiChartMouseEvents_Loaded(object sender, RoutedEventArgs e)
        {
            chart0.AnimateZoomExtents(TimeSpan.FromMilliseconds(1000));
            chart1.AnimateZoomExtents(TimeSpan.FromMilliseconds(1000));
        }

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

[Test]
        public void should_log_special_message_when_log_event_pool_is_exhausted()
        {
            LogManager.Shutdown();

            BasicConfigurator.Configure(new ZeroLogBasicConfiguration
            {
                Appenders = { _testAppender },
                LogEventQueueSize = 10,
                LogEventPoolExhaustionStrategy = LogEventPoolExhaustionStrategy.DropLogMessageAndNotifyAppenders
            });

            var log = LogManager.GetLogger(typeof(LogManagerTests));

            var actualLogEvents = new List<ILogEvent>();
            for (var i = 0; i < 10; i++)
            {
                actualLogEvents.Add(log.Debug());
            }

            var signal = _testAppender.SetMessageCountTarget(1);

            log.Debug().Append("this is not going to happen").Log();

            Check.That(signal.Wait(TimeSpan.FromMilliseconds(100))).IsTrue();

            Check.That(_testAppender.LoggedMessages.Last()).Contains("Log message skipped due to LogEvent pool exhaustion.");
        }

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

private void OnLoaded(object sender, RoutedEventArgs e)
        {
            SetupCharts();
            UpdateIndicators();

            var dataSubscription = _dataProvider.Data
                .Buffer(TimeSpan.FromMilliseconds(50))
                .ObserveOn(SynchronizationContext.Current)
                .Do(UpdateCharts)
                .Subscribe();

            var indicatorSubscription = Observable
                .Interval(TimeSpan.FromSeconds(1))
                .ObserveOn(SynchronizationContext.Current)
                .Do(UpdateIndicators)
                .Subscribe();

            _dataSubscription = new CompositeDisposable(dataSubscription, indicatorSubscription);
        }

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

public void AddCircuitBreaker(IConfigurationSection configurationSection)
        {
            UraganoSettings.CircuitBreakerOptions = new CircuitBreakerOptions
            {
                Timeout = TimeSpan.FromMilliseconds(configurationSection.GetValue<int>("timeout")),
                Retry = configurationSection.GetValue<int>("retry"),
                ExceptionsAllowedBeforeBreaking = configurationSection.GetValue<int>("ExceptionsAllowedBeforeBreaking"),
                DurationOfBreak = TimeSpan.FromMilliseconds(configurationSection.GetValue<int>("DurationOfBreak")),
                MaxParallelization = configurationSection.GetValue<int>("MaxParallelization"),
                MaxQueuingActions = configurationSection.GetValue<int>("MaxQueuingActions")
            };
        }

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

private void ZoomExtents()
        {
            ViewportManager.BeginInvoke(() =>
            {
                ViewportManager.AnimateZoomExtents(TimeSpan.FromMilliseconds(500));
            });
        }

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

[Test]
        public void should_wait_for_event_when_log_event_pool_is_exhausted()
        {
            LogManager.Shutdown();

            BasicConfigurator.Configure(new ZeroLogBasicConfiguration
            {
                Appenders = { _testAppender },
                LogEventQueueSize = 10,
                LogEventPoolExhaustionStrategy = LogEventPoolExhaustionStrategy.WaitForLogEvent
            });

            var log = LogManager.GetLogger(typeof(LogManagerTests));

            var actualLogEvents = new List<ILogEvent>();
            for (var i = 0; i < 10; i++)
            {
                actualLogEvents.Add(log.Debug());
            }

            var signal = _testAppender.SetMessageCountTarget(2);
            var logCompletedSignal = new ManualResetEvent(false);

            Task.Run(() =>
            {
                log.Debug().Append("this is not going to happen").Log();
                logCompletedSignal.Set();
            });

            Check.That(logCompletedSignal.WaitOne(TimeSpan.FromMilliseconds(100))).IsFalse();

            actualLogEvents[0].Log();

            Check.That(logCompletedSignal.WaitOne(TimeSpan.FromMilliseconds(100))).IsTrue();
            Check.That(signal.Wait(TimeSpan.FromMilliseconds(100))).IsTrue();
        }

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

private void AnimateExpand(object definition)
        {
            double currentValue;

            // Setup the animation and StoryBoard
            DoubleAnimation gridLengthAnimation = new DoubleAnimation() { Duration = new Duration(TimeSpan.FromMilliseconds(_animationTimeMillis)) };
            Storyboard sb = new Storyboard();

            // Add the animation to the StoryBoard
            sb.Children.Add(gridLengthAnimation);

            if (_gridCollapseDirection == GridCollapseDirection.Rows)
            {
                // Specify the target RowDefinition and property (Height) that will be altered by the animation.
                this.AnimatingRow = (RowDefinition)definition;
                Storyboard.SetTarget(gridLengthAnimation, this);
                Storyboard.SetTargetProperty(gridLengthAnimation, new PropertyPath("RowHeightAnimation"));

                currentValue = AnimatingRow.ActualHeight;
            }
            else
            {
                // Specify the target ColumnDefinition and property (Width) that will be altered by the animation.
                this.AnimatingColumn = (ColumnDefinition)definition;
                Storyboard.SetTarget(gridLengthAnimation, this);
                Storyboard.SetTargetProperty(gridLengthAnimation, new PropertyPath("ColWidthAnimation"));

                currentValue = AnimatingColumn.ActualWidth;
            }
            gridLengthAnimation.From = currentValue;
            gridLengthAnimation.To = _savedActualValue;

            // Start the StoryBoard.
            sb.Begin();
        }

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

public static ConnectionStringBuilder Parse(string connectionString)
        {
            var ret = new ConnectionStringBuilder();
            if (string.IsNullOrEmpty(connectionString)) return ret;

            //支持密码中带有逗号,将原有 split(',') 改成以下处理方式
            var vs = Regex.Split(connectionString, @"\,([\w \t\r\n]+)=", RegexOptions.Multiline);
            ret.Host = vs[0].Trim();

            for (var a = 1; a < vs.Length; a += 2)
            {
                var kv = new[] { Regex.Replace(vs[a].ToLower().Trim(), @"[ \t\r\n]", ""), vs[a + 1] };
                switch (kv[0])
                {
                    case "ssl": if (kv.Length > 1 && kv[1].ToLower().Trim() == "true") ret.Ssl = true; break;
                    case "protocol": if (kv.Length > 1 && kv[1].ToUpper().Trim() == "RESP3") ret.Protocol = RedisProtocol.RESP3; break;
                    case "userid":
                    case "user": if (kv.Length > 1) ret.User = kv[1].Trim(); break;
                    case "preplacedword": if (kv.Length > 1) ret.Preplacedword = kv[1]; break;
                    case "database":
                    case "defaultdatabase": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var database) && database > 0) ret.Database = database; break;

                    case "prefix": if (kv.Length > 1) ret.Prefix = kv[1].Trim(); break;
                    case "name":
                    case "clientname": if (kv.Length > 1) ret.ClientName = kv[1].Trim(); break;
                    case "encoding": if (kv.Length > 1) ret.Encoding = Encoding.GetEncoding(kv[1].Trim()); break;

                    case "idletimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var idleTimeout) && idleTimeout > 0) ret.IdleTimeout = TimeSpan.FromMilliseconds(idleTimeout); break;
                    case "connecttimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var connectTimeout) && connectTimeout > 0) ret.ConnectTimeout = TimeSpan.FromMilliseconds(connectTimeout); break;
                    case "receivetimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var receiveTimeout) && receiveTimeout > 0) ret.ReceiveTimeout = TimeSpan.FromMilliseconds(receiveTimeout); break;
                    case "sendtimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var sendTimeout) && sendTimeout > 0) ret.SendTimeout = TimeSpan.FromMilliseconds(sendTimeout); break;

                    case "poolsize":
                    case "maxpoolsize": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var maxPoolSize) && maxPoolSize > 0) ret.MaxPoolSize = maxPoolSize; break;
                    case "minpoolsize": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var minPoolSize) && minPoolSize > 0) ret.MinPoolSize = minPoolSize; break;
                    case "retry": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var retry) && retry > 0) ret.Retry = retry; break;
                }
            }
            return ret;
        }

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

private static void CheckboxChecked(object sender, RoutedEventArgs e)
        {
            var checkbox = sender as CheckBox;
            var scs = checkbox.FindVisualParent<SciChartSurface>();
            if (scs != null) scs.AnimateZoomExtents(TimeSpan.FromMilliseconds(500));
        }

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

[Test]
        public unsafe void should_not_throw_if_formatting_fails_when_appending_formatted_arguments()
        {
            LogManager.RegisterEnum<DayOfWeek>();
            var log = LogManager.GetLogger(typeof(LogManagerTests));
            var signal = _testAppender.SetMessageCountTarget(1);

            var guid = Guid.NewGuid();
            var date = new DateTime(2017, 02, 24, 16, 51, 51);
            var timespan = date.TimeOfDay;
            var asciiString = new[] { (byte)'a', (byte)'b', (byte)'c' };

            fixed (byte* pAsciiString = asciiString)
            {
                log.Info()
                   .Append("Hello")
                   .Append(false)
                   .Append((byte)1)
                   .Append('a')
                   .Append((short)2)
                   .Append(3)
                   .Append((long)4)
                   .Append(5f)
                   .Append(6d)
                   .Append(7m)
                   .Append(guid, "meh, this is going to break formatting")
                   .Append(date)
                   .Append(timespan)
                   .AppendAsciiString(asciiString, asciiString.Length)
                   .AppendAsciiString(pAsciiString, asciiString.Length)
                   .AppendEnum(DayOfWeek.Friday)
                   .Log();
            }

            signal.Wait(TimeSpan.FromMilliseconds(100));

            var logMessage = _testAppender.LoggedMessages.Single();
            Check.That(logMessage).Equals("An error occured during formatting: Unknown format specifier 'meh, this is going to break formatting'. - Arguments: \"Hello\", False, 1, 'a', 2, 3, 4, 5, 6, 7, " + guid + ", 2017-02-24 16:51:51.000, 16:51:51, \"abc\", \"abc\", Friday");
        }

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 : UraganoBuilder.cs
License : MIT License
Project Creator : 1100100

public void AddCircuitBreaker<TCircuitBreakerEvent>(int timeout = 3000, int retry = 3,
            int exceptionsAllowedBeforeBreaking = 10, int durationOfBreak = 60000, int maxParallelization = 0, int maxQueuingActions = 0) where TCircuitBreakerEvent : ICircuitBreakerEvent
        {
            UraganoSettings.CircuitBreakerOptions = new CircuitBreakerOptions
            {
                Timeout = TimeSpan.FromMilliseconds(timeout),
                Retry = retry,
                ExceptionsAllowedBeforeBreaking = exceptionsAllowedBeforeBreaking,
                DurationOfBreak = TimeSpan.FromMilliseconds(durationOfBreak),
                MaxParallelization = maxParallelization,
                MaxQueuingActions = maxQueuingActions
            };
            RegisterSingletonService(typeof(ICircuitBreakerEvent), typeof(TCircuitBreakerEvent));
        }

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

private void AnimateCollapse(object definition)
        {
            double currentValue;

            // Setup the animation and StoryBoard
            DoubleAnimation gridLengthAnimation = new DoubleAnimation() { Duration = new Duration(TimeSpan.FromMilliseconds(_animationTimeMillis)) };
            Storyboard sb = new Storyboard();

            // Add the animation to the StoryBoard
            sb.Children.Add(gridLengthAnimation);

            if (_gridCollapseDirection == GridCollapseDirection.Rows)
            {
                // Specify the target RowDefinition and property (Height) that will be altered by the animation.
                this.AnimatingRow = (RowDefinition)definition;
                Storyboard.SetTarget(gridLengthAnimation, this);
                Storyboard.SetTargetProperty(gridLengthAnimation, new PropertyPath("RowHeightAnimation"));

                currentValue = AnimatingRow.ActualHeight;
            }
            else
            {
                // Specify the target ColumnDefinition and property (Width) that will be altered by the animation.
                this.AnimatingColumn = (ColumnDefinition)definition;
                Storyboard.SetTarget(gridLengthAnimation, this);
                Storyboard.SetTargetProperty(gridLengthAnimation, new PropertyPath("ColWidthAnimation"));

                currentValue = AnimatingColumn.ActualWidth;
            }

            gridLengthAnimation.From = currentValue;
            gridLengthAnimation.To = 0;

            // Start the StoryBoard.
            sb.Begin();
        }

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

[Test]
        public void should_flush_appenders_when_not_logging_messages()
        {
            var log = LogManager.GetLogger(typeof(LogManagerTests));
            var signal = _testAppender.SetMessageCountTarget(3);
            _testAppender.WaitOnWriteEvent = new ManualResetEventSlim(false);

            log.Info("Foo");
            log.Info("Bar");
            log.Info("Baz");

            _testAppender.WaitOnWriteEvent.Set();
            signal.Wait(TimeSpan.FromMilliseconds(500));

            Wait.Until(() => _testAppender.FlushCount == 1, TimeSpan.FromSeconds(1));

            log.Info("Foo");
            Wait.Until(() => _testAppender.FlushCount == 2, TimeSpan.FromSeconds(1));
        }

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

private void Work()
        {
            try
            {
                StreamReader reader = new StreamReader(Connection);
                StreamWriter writer = new StreamWriter(Connection);

                int StatusPollInterval = Properties.Settings.Default.StatusPollInterval;

                int ControllerBufferSize = Properties.Settings.Default.ControllerBufferSize;
                BufferState = 0;

                TimeSpan WaitTime = TimeSpan.FromMilliseconds(0.5);
                DateTime LastStatusPoll = DateTime.Now + TimeSpan.FromSeconds(0.5);
                DateTime StartTime = DateTime.Now;

                DateTime LastFilePosUpdate = DateTime.Now;
                bool filePosChanged = false;

                bool SendMacroStatusReceived = false;

                writer.Write("\n$G\n");
                writer.Write("\n$#\n");
                writer.Flush();

                while (true)
                {
                    Task<string> lineTask = reader.ReadLineAsync();

                    while (!lineTask.IsCompleted)
                    {
                        if (!Connected)
                        {
                            return;
                        }

                        while (ToSendPriority.Count > 0)
                        {
                            writer.Write((char)ToSendPriority.Dequeue());
                            writer.Flush();
                        }
                        if (Mode == OperatingMode.SendFile)
                        {
                            if (File.Count > FilePosition && (File[FilePosition].Length + 1) < (ControllerBufferSize - BufferState))
                            {
                                string send_line = File[FilePosition].Replace(" ", ""); // don't send whitespace to machine

                                writer.Write(send_line);
                                writer.Write('\n');
                                writer.Flush();

                                RecordLog("> " + send_line);

                                RaiseEvent(UpdateStatus, send_line);
                                RaiseEvent(LineSent, send_line);

                                BufferState += send_line.Length + 1;

                                Sent.Enqueue(send_line);

                                if (PauseLines[FilePosition] && Properties.Settings.Default.PauseFileOnHold)
                                {
                                    Mode = OperatingMode.Manual;
                                }

                                if (++FilePosition >= File.Count)
                                {
                                    Mode = OperatingMode.Manual;
                                }

                                filePosChanged = true;
                            }
                        }
                        else if (Mode == OperatingMode.SendMacro)
                        {
                            switch (Status)
                            {
                                case "Idle":
                                    if (BufferState == 0 && SendMacroStatusReceived)
                                    {
                                        SendMacroStatusReceived = false;

                                        string send_line = (string)ToSendMacro.Dequeue();

                                        send_line = Calculator.Evaluate(send_line, out bool success);

                                        if (!success)
                                        {
                                            ReportError("Error while evaluating macro!");
                                            ReportError(send_line);

                                            ToSendMacro.Clear();
                                        }
                                        else
                                        {
                                            send_line = send_line.Replace(" ", "");

                                            writer.Write(send_line);
                                            writer.Write('\n');
                                            writer.Flush();

                                            RecordLog("> " + send_line);

                                            RaiseEvent(UpdateStatus, send_line);
                                            RaiseEvent(LineSent, send_line);

                                            BufferState += send_line.Length + 1;

                                            Sent.Enqueue(send_line);
                                        }
                                    }
                                    break;
                                case "Run":
                                case "Hold":
                                    break;
                                default:    // grbl is in some kind of alarm state
                                    ToSendMacro.Clear();
                                    break;
                            }

                            if (ToSendMacro.Count == 0)
                                Mode = OperatingMode.Manual;
                        }
                        else if (ToSend.Count > 0 && (((string)ToSend.Peek()).Length + 1) < (ControllerBufferSize - BufferState))
                        {
                            string send_line = ((string)ToSend.Dequeue()).Replace(" ", "");

                            writer.Write(send_line);
                            writer.Write('\n');
                            writer.Flush();

                            RecordLog("> " + send_line);

                            RaiseEvent(UpdateStatus, send_line);
                            RaiseEvent(LineSent, send_line);

                            BufferState += send_line.Length + 1;

                            Sent.Enqueue(send_line);
                        }


                        DateTime Now = DateTime.Now;

                        if ((Now - LastStatusPoll).TotalMilliseconds > StatusPollInterval)
                        {
                            writer.Write('?');
                            writer.Flush();
                            LastStatusPoll = Now;
                        }

                        //only update file pos every X ms
                        if (filePosChanged && (Now - LastFilePosUpdate).TotalMilliseconds > 500)
                        {
                            RaiseEvent(FilePositionChanged);
                            LastFilePosUpdate = Now;
                            filePosChanged = false;
                        }

                        Thread.Sleep(WaitTime);
                    }

                    string line = lineTask.Result;

                    RecordLog("< " + line);

                    if (line == "ok")
                    {
                        if (Sent.Count != 0)
                        {
                            BufferState -= ((string)Sent.Dequeue()).Length + 1;
                        }
                        else
                        {
                            MainWindow.Logger.Info("Received OK without anything in the Sent Buffer");
                            BufferState = 0;
                        }
                    }
                    else
                    {
                        if (line.StartsWith("error:"))
                        {
                            if (Sent.Count != 0)
                            {
                                string errorline = (string)Sent.Dequeue();

                                RaiseEvent(ReportError, $"{line}: {errorline}");
                                BufferState -= errorline.Length + 1;
                            }
                            else
                            {
                                if ((DateTime.Now - StartTime).TotalMilliseconds > 200)
                                    RaiseEvent(ReportError, $"Received <{line}> without anything in the Sent Buffer");

                                BufferState = 0;
                            }

                            Mode = OperatingMode.Manual;
                        }
                        else if (line.StartsWith("<"))
                        {
                            RaiseEvent(ParseStatus, line);
                            SendMacroStatusReceived = true;
                        }
                        else if (line.StartsWith("[PRB:"))
                        {
                            RaiseEvent(ParseProbe, line);
                            RaiseEvent(LineReceived, line);
                        }                      
                        else if (line.StartsWith("["))
                        {
                            RaiseEvent(UpdateStatus, line);
                            RaiseEvent(LineReceived, line);
                        }
                        else if (line.StartsWith("ALARM"))
                        {
                            RaiseEvent(ReportError, line);
                            Mode = OperatingMode.Manual;
                            ToSend.Clear();
                            ToSendMacro.Clear();
                        }
                        else if (line.Length > 0)
                            RaiseEvent(LineReceived, line);
                    }
                }
            }
            catch (Exception ex)
            {
                RaiseEvent(ReportError, $"Fatal Error in Work Loop: {ex.Message}");
                RaiseEvent(() => Disconnect());
            }
        }

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

public void AddOptions(IConfigurationSection configuration)
        {
            if (!configuration.Exists())
                return;
            foreach (var section in configuration.GetChildren())
            {
                switch (section.Key.ToLower())
                {
                    case "threadpool_minthreads":
                        UraganoOptions.SetOption(UraganoOptions.ThreadPool_MinThreads, configuration.GetValue<int>(section.Key));
                        break;
                    case "threadpool_completionportthreads":
                        UraganoOptions.SetOption(UraganoOptions.ThreadPool_CompletionPortThreads, configuration.GetValue<int>(section.Key));
                        break;
                    case "consul_node_status_refresh_interval":
                        UraganoOptions.SetOption(UraganoOptions.Consul_Node_Status_Refresh_Interval, TimeSpan.FromMilliseconds(configuration.GetValue<int>(section.Key)));
                        break;
                    case "server_dotnetty_channel_sobacklog":
                        UraganoOptions.SetOption(UraganoOptions.Server_DotNetty_Channel_SoBacklog, configuration.GetValue<int>(section.Key));
                        break;
                    case "dotnetty_connect_timeout":
                        UraganoOptions.SetOption(UraganoOptions.DotNetty_Connect_Timeout, TimeSpan.FromMilliseconds(configuration.GetValue<int>(section.Key)));
                        break;
                    case "dotnetty_enable_libuv":
                        UraganoOptions.SetOption(UraganoOptions.DotNetty_Enable_Libuv, configuration.GetValue<bool>(section.Key));
                        break;
                    case "dotnetty_event_loop_count":
                        UraganoOptions.SetOption(UraganoOptions.DotNetty_Event_Loop_Count, configuration.GetValue<int>(section.Key));
                        break;
                    case "remoting_invoke_cancellationtokensource_timeout":
                        UraganoOptions.SetOption(UraganoOptions.Remoting_Invoke_CancellationTokenSource_Timeout, TimeSpan.FromMilliseconds(configuration.GetValue<int>(section.Key)));
                        break;
                    case "output_dynamicproxy_sourcecode":
                        UraganoOptions.SetOption(UraganoOptions.Output_DynamicProxy_SourceCode, configuration.GetValue<bool>(section.Key));
                        break;
                }

            }
        }

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

public void AddCircuitBreaker(int timeout = 3000, int retry = 3, int exceptionsAllowedBeforeBreaking = 10,
            int durationOfBreak = 60000, int maxParallelization = 0, int maxQueuingActions = 0)
        {
            UraganoSettings.CircuitBreakerOptions = new CircuitBreakerOptions
            {
                Timeout = TimeSpan.FromMilliseconds(timeout),
                Retry = retry,
                ExceptionsAllowedBeforeBreaking = exceptionsAllowedBeforeBreaking,
                DurationOfBreak = TimeSpan.FromMilliseconds(durationOfBreak),
                MaxParallelization = maxParallelization,
                MaxQueuingActions = maxQueuingActions
            };
        }

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

public async Task StopAsync()
        {
            Logger.LogInformation("Stopping uragano server...");
            await Channel.CloseAsync();
            await BossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            await WorkerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            Logger.LogInformation("The uragano server has stopped.");
        }

19 View Source File : StateMachines.cs
License : MIT License
Project Creator : 71

[Fact]
        public async void ShouldCreateSimpleASM()
        {
            Task sleepTask = Task.Delay(1000);

            AsyncExpression async = X.Async(
                X.Await(X.Link(sleepTask))
            );

            DateTime before = DateTime.Now;

            await async.Compile();

            TimeSpan timeTaken = DateTime.Now - before;

            timeTaken.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromMilliseconds(1000));
        }

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

private void OnStart()
        {
            if (!IsLoaded) return;

            int countU, countV;
            switch (DataCombo.SelectedIndex)
            {
                case 0:
                    countU = countV = 10;
                    break;
                case 1:
                    countU = countV = 50;
                    break;
                case 2:
                    countU = countV = 100;
                    break;
                case 3:
                    countU = countV = 500;
                    break;
                case 4:
                    countU = countV = 1000;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            lock (_syncRoot)
            {
                OnStop();
            }

            BitmapImage bitmapImage = new BitmapImage();

            // Load image from resources
            bitmapImage.BeginInit();
            bitmapImage.CacheOption = BitmapCacheOption.OnDemand;
            bitmapImage.CreateOptions = BitmapCreateOptions.DelayCreation;
            bitmapImage.DecodePixelWidth = countU;
            bitmapImage.DecodePixelHeight = countV;
            bitmapImage.UriSource = new Uri("pack://application:,,,/SciChart.Examples.ExternalDependencies;component/Resources/Images/globe_heightmap.png");
            bitmapImage.EndInit();

            // Creating Geo height (displacement) map
            var geoHeightMap = new double[countU, countV];
            int nStride = (bitmapImage.PixelWidth * bitmapImage.Format.BitsPerPixel + 7) / 8;
            int bytsPerPixel = bitmapImage.Format.BitsPerPixel / 8;
            byte[] pixelByteArray = new byte[bitmapImage.PixelWidth * nStride];
            bitmapImage.CopyPixels(pixelByteArray, nStride, 0);
            for (int v = 0; v < countV; v++)
            {
                for (var u = 0; u < countU; u++)
                {
                    int pixelIndex = v * nStride + u * bytsPerPixel;
                    var offset = pixelByteArray[pixelIndex] / 255.0f;
                    geoHeightMap[v, u] = offset;
                }
            }

            var dataSeries = new EllipsoidDataSeries3D<double>(countU, countV)
            {
                SeriesName = "Geo Mesh",
                A = 6,
                B = 6,
                C = 6
            };

            var frontBuffer = dataSeries.InternalArray;
            var backBuffer = new GridData<double>(countU, countV).InternalArray;

            int frames = 0;
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromMilliseconds(20);
            _timer.Tick += (s, arg) =>
            {
                lock (_syncRoot)
                {
                    double heightOffsetsScale = sliderHeightOffsetsScale.Value;
                    double freq = (Math.Sin(frames++*0.1) + 1.0) / 2.0;

                    // Each set of geoHeightMap[i,j] schedules a redraw when the next Render event fires. Therefore, we suspend updates so that we can update the chart once
                    // We parallelize it by using Parallel.For for the outer loop
                    //  Equivalent of "for (int j = 0; j < countU; j++)"
                    // This will result in more CPU usage, but we wish to demo the performance of the actual rendering, not the slowness of generating test data! :)
                    Parallel.For(0, countV, i =>
                    {
                        var buf = frontBuffer;
                        for (int j = 0; j < countU; j++)
                        {
                            // Rotate (offset) J index
                            int rj = j + frames;
                            if (rj >= countU)
                            {
                                rj -= countU * (rj / countU);
                            }

                            buf[i][j] = geoHeightMap[i, rj] + Math.Pow(geoHeightMap[i, rj], freq * 10.0) * heightOffsetsScale;
                        }
                    });

                    using (dataSeries.SuspendUpdates(false, true))
                    {
                        dataSeries.CopyFrom(frontBuffer);
                        var temp = backBuffer;
                        backBuffer = frontBuffer;
                        frontBuffer = temp;
                    }
                }
            };
            SurfaceMesh.DataSeries = dataSeries;
            _timer.Start();
            StartButton.IsEnabled = false;
            PauseButton.IsEnabled = true;
        }

See More Examples