public PreviewItem() { CopyCommand = ReactiveCommand.CreateFromTask <object>(async obj => { if (obj.ToString() is { } text) { _copyButtonPressedStopwatch = Stopwatch.StartNew(); await Application.Current.Clipboard.SetTextAsync(text); } }); this.WhenAnyValue( x => x.CopyParameter, x => x.IsPointerOver, x => x.PrivacyModeEnabled, (copyParameter, isPointerOver, privacyModeEnabled) => !string.IsNullOrEmpty(copyParameter?.ToString()) && isPointerOver && !privacyModeEnabled) .Subscribe(async value => { if (_copyButtonPressedStopwatch is { } sw) { var elapsedMilliseconds = sw.ElapsedMilliseconds; var millisecondsToWait = 1050 - (int)elapsedMilliseconds; if (millisecondsToWait > 0) { await Task.Delay(millisecondsToWait); } _copyButtonPressedStopwatch = null; } CopyButtonVisibility = value; }); }
public static void DownloadText(string address, Stopwatch?watch, DownloadTextResultHandler callback, bool ignoreCache, out bool isFound) { string FileName = LocalFileName(address); string FilePath = Path.GetDirectoryName(FileName); if (!ignoreCache && File.Exists(FileName)) { using (FileStream Stream = new FileStream(FileName, FileMode.Open, FileAccess.Read)) { using (StreamReader Reader = new StreamReader(Stream)) { string Content = Reader.ReadToEnd(); isFound = !string.IsNullOrEmpty(Content); callback(isFound, Content); } } } else { if (!Directory.Exists(FilePath)) { Directory.CreateDirectory(FilePath); } Task <Tuple <bool, string?> > DownloadTask = new Task <Tuple <bool, string?> >(() => { return(ExecuteDownloadText(address, watch)); }); DownloadTask.Start(); OnCheckDownload(DownloadTask, address, callback, out isFound); } }
public async Task OnMessageAsync(MessageContext message, HttpApiClient api) { if (s_stopwatch == null) { s_stopwatch = Stopwatch.StartNew(); } if (s_nextCheck < s_stopwatch.ElapsedMilliseconds) { const int IntervalMilliseconds = 10 * 60_000; s_nextCheck = s_stopwatch.ElapsedMilliseconds + IntervalMilliseconds; var cmbc = await HttpApi.Resolve <ICmbcCreditRate>().GetRates().ConfigureAwait(false); var cmbcJson = JsonSerializer.Serialize(cmbc); if (cmbcJson != s_cmbcJson) { s_cmbcJson = cmbcJson; _logger.LogInformation($"CMBC Changed: {cmbcJson}"); } var cib = await HttpApi.Resolve <ICibRate>().GetRates().ConfigureAwait(false); var cibJson = JsonSerializer.Serialize(cib); if (cibJson != s_cibJson) { s_cibJson = cibJson; _logger.LogInformation($"CIB Changed: {cibJson}"); } } }
private void RunMigration() { _toBlock = MigrateToBlockNumber; if (_toBlock > 0) { _cancellationTokenSource = new CancellationTokenSource(); _disposeStack.Push(this); _stopwatch = Stopwatch.StartNew(); _migrationTask = Task.Run(() => RunMigration(_cancellationTokenSource.Token)) .ContinueWith(x => { if (x.IsFaulted && _logger.IsError) { _stopwatch.Stop(); _logger.Error(GetLogMessage("failed", $"Error: {x.Exception}"), x.Exception); } }); } else { if (_logger.IsDebug) { _logger.Debug("ReceiptsDb migration not needed."); } } }
public void Start() { _running = RUN_STATUS.RUNNING; watch = System.Diagnostics.Stopwatch.StartNew(); Log.Information(Strings.Get("Starting"), GetType().Name); }
private PingReply SendCancellablePing( IPAddress targetAddress, int timeout, byte[] buffer, PingOptions pingOptions, Stopwatch?timer = null) { try { _sender = new Ping(); timer?.Start(); // 'SendPingAsync' always uses the default synchronization context (threadpool). // This is what we want to avoid the deadlock resulted by async work being scheduled back to the // pipeline thread due to a change of the current synchronization context of the pipeline thread. return(_sender.SendPingAsync(targetAddress, timeout, buffer, pingOptions).GetAwaiter().GetResult()); } catch (PingException ex) when(ex.InnerException is TaskCanceledException) { // The only cancellation we have implemented is on pipeline stops via StopProcessing(). throw new PipelineStoppedException(); } finally { timer?.Stop(); _sender?.Dispose(); _sender = null; } }
private void RunBloomMigration() { if (_api.DisposeStack == null) { throw new StepDependencyException(nameof(_api.DisposeStack)); } if (_api.BloomStorage == null) { throw new StepDependencyException(nameof(_api.BloomStorage)); } if (_api.BloomStorage.NeedsMigration) { _cancellationTokenSource = new CancellationTokenSource(); _api.DisposeStack.Push(this); _stopwatch = Stopwatch.StartNew(); _migrationTask = Task.Run(() => RunBloomMigration(_cancellationTokenSource.Token)) .ContinueWith(x => { if (x.IsFaulted && _logger.IsError) { _stopwatch.Stop(); _logger.Error(GetLogMessage("failed", $"Error: {x.Exception}"), x.Exception); } }); } }
/// <summary> /// Struct initializer. /// </summary> private PerformanceMeasurement( LoggingContext parentLoggingContext, PerformanceCollector.Aggregator?aggregator, string?phaseFriendlyName, Action <LoggingContext> endAction) { Contract.RequiresNotNull(parentLoggingContext); Contract.RequiresNotNull(endAction); LoggingContext = new LoggingContext(parentLoggingContext, phaseFriendlyName); m_aggregator = aggregator; m_endAction = endAction; if (!string.IsNullOrWhiteSpace(phaseFriendlyName)) { m_stopwatch = new Stopwatch(); m_stopwatch.Start(); } else { m_stopwatch = null; } m_isDisposed = false; }
public virtual void ExecuteLayoutPass() { Dispatcher.UIThread.VerifyAccess(); if (_disposed) { return; } if (!_running) { _running = true; Stopwatch?stopwatch = null; const LogEventLevel timingLogLevel = LogEventLevel.Information; bool captureTiming = Logger.IsEnabled(timingLogLevel, LogArea.Layout); if (captureTiming) { Logger.TryGet(timingLogLevel, LogArea.Layout)?.Log( this, "Started layout pass. To measure: {Measure} To arrange: {Arrange}", _toMeasure.Count, _toArrange.Count); stopwatch = new Stopwatch(); stopwatch.Start(); } _toMeasure.BeginLoop(MaxPasses); _toArrange.BeginLoop(MaxPasses); for (var pass = 0; pass < MaxPasses; ++pass) { InnerLayoutPass(); if (!RaiseEffectiveViewportChanged()) { break; } } _toMeasure.EndLoop(); _toArrange.EndLoop(); if (captureTiming) { stopwatch !.Stop(); Logger.TryGet(timingLogLevel, LogArea.Layout)?.Log(this, "Layout pass finished in {Time}", stopwatch.Elapsed); } } _queued = false; LayoutUpdated?.Invoke(this, EventArgs.Empty); }
public Win32Job(SafeHandle hJob, SafeHandle hProcess, bool propagateOnChildProcesses, long clockTimeLimitInMilliseconds = 0L) { this.hJob = hJob; this.hProcess = hProcess; this.propagateOnChildProcesses = propagateOnChildProcesses; this.clockTimeLimitInMilliseconds = clockTimeLimitInMilliseconds; stopWatch = clockTimeLimitInMilliseconds > 0 ? Stopwatch.StartNew() : null; }
protected override bool OnDrawn(Context cr) { Stopwatch?sw = null; if (this.Log().IsEnabled(LogLevel.Trace)) { sw = Stopwatch.StartNew(); this.Log().Trace($"Render {renderCount++}"); } var scaledWidth = (int)(AllocatedWidth * _dpi); var scaledHeight = (int)(AllocatedHeight * _dpi); // reset the surfaces (skia/cairo) and bitmap if the size has changed if (_surface == null || scaledWidth != _bwidth || scaledHeight != _bheight) { _gtkSurface?.Dispose(); _surface?.Dispose(); _bitmap?.Dispose(); var info = new SKImageInfo(scaledWidth, scaledHeight, _colorType, SKAlphaType.Premul); _bitmap = new SKBitmap(info); _bwidth = _bitmap.Width; _bheight = _bitmap.Height; var pixels = _bitmap.GetPixels(out _); _surface = SKSurface.Create(info, pixels); _gtkSurface = new ImageSurface(pixels, Format.Argb32, _bwidth, _bheight, _bwidth * 4); } var canvas = _surface.Canvas; using (new SKAutoCanvasRestore(canvas, true)) { canvas.Clear(BackgroundColor); canvas.Scale(_dpi); WUX.Window.Current.Compositor.Render(_surface); } _gtkSurface !.MarkDirty(); cr.Save(); cr.Scale(1 / _dpi, 1 / _dpi); cr.SetSourceSurface(_gtkSurface, 0, 0); cr.Paint(); cr.Restore(); if (this.Log().IsEnabled(LogLevel.Trace)) { sw?.Stop(); this.Log().Trace($"Frame: {sw?.Elapsed}"); } return(true); }
private void UpdateStatusBar(StatusBarBase.Panel panel, string type, Stopwatch?sw) { if (sw != null) { panel.Text = "Generated " + type + " in " + sw.ElapsedMilliseconds + " ms."; } else { panel.Text = "Loaded " + type + "."; } }
public PreviewItem() { CopyCommand = ReactiveCommand.CreateFromTask <object>(async obj => { if (obj.ToString() is { } text) { _copyButtonPressedStopwatch = Stopwatch.StartNew(); if (Application.Current is { Clipboard: { } clipboard }) { await clipboard.SetTextAsync(text); } }
/// <summary>Логика выполнения - Выполнить операцию</summary> private Task OnStartCommandExecutedAsync(object?p) { Error = null; _Cancellation = new CancellationTokenSource(); var cancel = _Cancellation.Token; _Timer = Stopwatch.StartNew(); _OperationTask = _Execute(p, new Progress <double>(progress => Progress = progress), cancel); InProgress = true; _ = _OperationTask.ContinueWith(OnOperationCompletedAsync, CancellationToken.None); return(_OperationTask); }
public void Start() { if (twiddleTimer != null) { return; } if (showElapsedTime) { watch = new Stopwatch(); watch.Start(); } twiddleTimer = new Timer(Twiddle); twiddleTimer.Change(250, twiddleInterval); }
/// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="alsoManaged"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> private void Dispose(bool alsoManaged) { if (_isDisposed) { return; } if (alsoManaged) { Add(_identifier, _stopwatch?.Elapsed ?? default); _stopwatch?.Stop(); } _stopwatch = null; _isDisposed = true; }
public static async ValueTask FillAsync(this NetworkStream networkStream, Memory <byte> buffer, CancellationToken cancellationToken = default) { Stopwatch?timer = null; int timeout = networkStream.ReadTimeout; if (timeout != -1) { timer = new Stopwatch(); timer.Start(); } int index = 0; while (index < buffer.Length) { if (timer is { } && (int)timer.ElapsedMilliseconds > timeout)
private static void RunTask(BindTask task, Stopwatch?sw) { foreach (var typeMap in task.TypeMaps) { var toAdd = new List <KeyValuePair <string, string> >(); foreach (var kvp in typeMap) { if (kvp.Key.StartsWith("$include")) { toAdd.Add(kvp); } } foreach (var kvp in toAdd) { var includedMap = JsonConvert.DeserializeObject <Dictionary <string, string> > (File.ReadAllText(kvp.Value)); typeMap.Remove(kvp.Key); foreach (var includedKvp in includedMap) { typeMap.Add(includedKvp.Key, includedKvp.Value); } } } Profile profile; if (ShouldConvert(task.Controls)) { Console.WriteLine("Profile conversion started!"); var tsb4 = sw?.Elapsed.TotalSeconds; var profiles = new List <Profile>(); if (task.Mode == ConverterMode.ConvertConstruct) { foreach (var src in task.Sources) { var rawProfiles = ProfileConverter.ReadProfiles ( task.ConverterOpts.Reader.ToLower() switch { "gl" => new OpenGLReader(), "cl" => new OpenCLReader(), "vk" => new VulkanReader(), _ => throw new ArgumentException("Couldn't find a reader with that name") }, task.ConverterOpts.Constructor.ToLower() switch
private PingReply SendCancellablePing( IPAddress targetAddress, int timeout, byte[] buffer, PingOptions pingOptions, Stopwatch?timer = null) { try { _sender = new Ping(); _sender.PingCompleted += OnPingComplete; timer?.Start(); _sender.SendAsync(targetAddress, timeout, buffer, pingOptions, this); _pingComplete.Wait(); timer?.Stop(); _pingComplete.Reset(); if (_pingCompleteArgs == null) { throw new PingException(string.Format( TestConnectionResources.NoPingResult, targetAddress, IPStatus.Unknown)); } if (_pingCompleteArgs.Cancelled) { // The only cancellation we have implemented is on pipeline stops via StopProcessing(). throw new PipelineStoppedException(); } if (_pingCompleteArgs.Error != null) { throw new PingException(_pingCompleteArgs.Error.Message, _pingCompleteArgs.Error); } return(_pingCompleteArgs.Reply); } finally { _sender?.Dispose(); _sender = null; } }
void UpdateTimer() { var ticksLeft = GetTicksLeft(); if (ticksLeft < 0) { StopTimer(); } else { if (timerStart is null) { timerStart = Stopwatch.StartNew(); } timer.Interval = TimeSpan.FromTicks(Math.Max(10000, ticksLeft)); timer.Start(); } }
private static void IpsGetter() { try { s_ips = GetLocalNetworkIPAddresses().ToArray(); } catch { // Choke all errors. // This is function is used for diagnostics // we don't want it to interrupt the process in any way s_ips = new string[1] { "Cannot get IPs" }; } s_showLocalIp = Stopwatch.StartNew(); }
private static Tuple <bool, string?> ExecuteDownloadText(string address, Stopwatch?watch) { try { HttpClient Request = new HttpClient(); Task <HttpResponseMessage> Message = Request.GetAsync(address); Message.Wait(); HttpResponseMessage Response = Message.Result; if (Response.StatusCode != HttpStatusCode.OK) { return(new Tuple <bool, string?>(false, null)); } HttpContent ResponseContent = Response.Content; Task <Stream> ReadTask = ResponseContent.ReadAsStreamAsync(); ReadTask.Wait(); using Stream ResponseStream = ReadTask.Result; Encoding Encoding = Encoding.ASCII; using StreamReader Reader = new StreamReader(ResponseStream, Encoding); string Content = Reader.ReadToEnd(); bool IsReadToEnd = Reader.EndOfStream; if (IsReadToEnd) { if (watch != null) { MinimalSleep(watch); } return(new Tuple <bool, string?>(true, Content)); } else { return(new Tuple <bool, string?>(true, null)); } } catch (Exception) { return(new Tuple <bool, string?>(false, null)); } }
public App(bool readSettings, Stopwatch startupStopwatch) { resourceManagerTokenCacheImpl = new ResourceManagerTokenCacheImpl(); // PERF: Init MEF on a BG thread. Results in slightly faster startup, eg. InitializeComponent() becomes a 'free' call on this UI thread initializeMEFTask = Task.Run(() => InitializeMEF(readSettings, useCache: readSettings)); this.startupStopwatch = startupStopwatch; resourceManagerTokenCacheImpl.TokensUpdated += ResourceManagerTokenCacheImpl_TokensUpdated; ResourceHelper.SetResourceManagerTokenCache(resourceManagerTokenCacheImpl); args = new AppCommandLineArgs(); AppDirectories.SetSettingsFilename(args.SettingsFilename); AddAppContextFixes(); InstallExceptionHandlers(); InitializeComponent(); UIFixes(); Exit += App_Exit; }
/// <summary> /// Runs the <see cref="Executor"/> asynchronously. /// </summary> /// <returns>The <see cref="Task"/>.</returns> internal Task RunExecutorAsync(object?args) { return(Task.Run(async() => { Trace(() => Logger.Default.Trace($"Executor '{InstanceId}' of Type '{GetType().Name}' started.")); _stopwatch = Stopwatch.StartNew(); State = ExecutionState.Started; if (!(await RunWrapperAsync(ExceptionHandling.Stop, async() => await StartedAsync().ConfigureAwait(false), this, false).ConfigureAwait(false)).WasSuccessful) { return; } if (State != ExecutionState.Started) { return; } Trace(() => Logger.Default.Trace($"Executor '{InstanceId}' running.")); State = ExecutionState.Running; _executionManager !.ExecutorAction(this, args); })); }
protected static async Task <TResult> TraceActionAsync <TContext, TResult>( DataConnection dataConnection, TraceOperation traceOperation, Func <TContext, string?>?commandText, TContext context, Func <DataConnection, TContext, CancellationToken, Task <TResult> > action, CancellationToken cancellationToken) { var now = DateTime.UtcNow; Stopwatch?sw = null; var sql = dataConnection.TraceSwitchConnection.TraceInfo ? commandText?.Invoke(context) : null; if (dataConnection.TraceSwitchConnection.TraceInfo) { sw = Stopwatch.StartNew(); dataConnection.OnTraceConnection(new TraceInfo(dataConnection, TraceInfoStep.BeforeExecute, traceOperation, true) { TraceLevel = TraceLevel.Info, CommandText = sql, StartTime = now, }); } try { var actionResult = await action(dataConnection, context, cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext); if (dataConnection.TraceSwitchConnection.TraceInfo) { dataConnection.OnTraceConnection(new TraceInfo(dataConnection, TraceInfoStep.AfterExecute, traceOperation, true) { TraceLevel = TraceLevel.Info, CommandText = sql, StartTime = now, ExecutionTime = sw !.Elapsed }); }
/// <summary> /// Initializes a new instance of the <see cref="PerformanceTimerAttribute"/> class. /// </summary> /// <param name="performanceMonitor">The performance monitor.</param> /// <param name="measurementClassification">The measurement classification.</param> private PerformanceTimerAttribute(IPerformanceMonitor performanceMonitor, IClassification?measurementClassification = null) { this._performanceMonitor = performanceMonitor; this._measurementClassification = measurementClassification; this._timer = new Stopwatch(); }
private GrepStatistics(bool enabled, Stopwatch?stopwatch = null) { Enabled = enabled; _stopwatch = stopwatch; }
public static async Task <int> Main(string[] args) { var showInfo = ConfigUtils.GetConfigBool("showInfo"); Stopwatch?programTimer = null; if (showInfo) { programTimer = Stopwatch.StartNew(); } Console.WriteLine(Funnies.Funnies.GetLine()); DownloadUtils.Init(); try { DownloadUtils.DeleteDownloads(); } catch (Exception) { } // Read Config.xml //string zipFile = ConfigUtils.GetConfigValue("zipFile"); string urlBase = ConfigUtils.GetConfigValue("urlBase"); var contextSettings = ConfigUtils.ParseConnectionSettings <DbConnectionSettings>("dataTable"); bool deleteDownloads = ConfigUtils.GetConfigBool("deleteDownloadsOnSuccess"); //CTID Location var ctiSettings = ConfigUtils.ParseConnectionSettings <CTI>("ctidLocation"); ctiSettings.Column = ConfigUtils.GetConfigValue("ctidLocation", "ctidfpColumn"); ctiSettings.ShapeColumn = ConfigUtils.GetConfigValue("ctidLocation", "shapeColumn"); // End CTID // Windoze can use Windows Auth, so user and password are not required if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && (contextSettings.IsUserOrPasswordEmpty || ctiSettings.IsUserOrPasswordEmpty)) { PrintMessageAndWait(NO_CREDENTIALS); return(-7); } #if !DEBUG if (string.IsNullOrWhiteSpace(dbServer) | string.IsNullOrEmpty(CTI.Server)) { PrintMessageAndWait(NO_SERVER); return(-8); } if (string.IsNullOrWhiteSpace(database) | string.IsNullOrEmpty(CTI.Database)) { PrintMessageAndWait(NO_DATABASE); return(-9); } #endif Stopwatch?timer = null; var now = DateTime.Now; DownloadUtils.CreateDownloadTempDirectory(); // This is only used for testing/LocalDB //using (var ctx = new Context(contextSettings)) //{ // ctx.EnsureDatabase(); //} if (showInfo) { if (!string.IsNullOrEmpty(urlBase)) { Console.WriteLine($"Connecting to {urlBase.Substring(8, urlBase.IndexOf(".gov") - 4)} - {now}"); } timer = Stopwatch.StartNew(); } // Download the things //await DownloadUtils.DownloadFileAsync(urlBase, zipFile); if (showInfo) { timer !.Stop(); Console.WriteLine($"Downloaded {DownloadUtils.GetDownloadSizeInMb()}MB in {timer.Elapsed.Minutes} minutes {timer.Elapsed.Seconds} seconds"); } //DownloadUtils.UnZip(zipFile); // Process the data Console.WriteLine(Funnies.Funnies.GetLine()); Console.Write("Performing some task... "); using (var progress = new ProgressBar()) { for (int i = 0; i <= 100; i++) { await DataParser.ParseFileAsync <IKeyed <object> >(DownloadUtils.GetLargestFileInDownload(), progress.Report, contextSettings); progress.Report((double)i / 100); System.Threading.Thread.Sleep(20); } } Console.WriteLine("Done."); if (showInfo) { programTimer !.Stop(); PrintMessageAndWait($"Execution completed in {programTimer.Elapsed.Hours} hours {programTimer.Elapsed.Minutes} minutes {programTimer.Elapsed.Seconds}.{programTimer.Elapsed.Milliseconds} seconds"); } if (deleteDownloads) { try { DownloadUtils.DeleteDownloads(); } catch (Exception e) { PrintMessageAndWait(e.Message); } } return(0); }
/// <summary> /// Starts the measurement. /// </summary> public void StartMeasurement() { _stopwatch = new Stopwatch(); _stopwatch.Start(); }
public void Start() { RunStatus = RUN_STATUS.RUNNING; watch = Stopwatch.StartNew(); Log.Information(Strings.Get("Starting"), GetType().Name); }