public async Task StopServiceProfilerAsync()

in src/ServiceProfiler.EventPipe.Otel/Azure.Monitor.OpenTelemetry.Profiler.Core/OpenTelemetryProfilerProvider.cs [108:181]


    public async Task<bool> StopServiceProfilerAsync(IProfilerSource source, CancellationToken cancellationToken = default)
    {
        _logger.LogInformation(StopProfilerTriggered);
        _logger.LogTrace("Entering {StopServiceProfilerAsync}.", nameof(StopServiceProfilerAsync));

        bool profilerStopped = false;

        if (source is null)
        {
            throw new ArgumentNullException(nameof(source));
        }

        if (!IsSemaphoreTaken)
        {
            _logger.LogDebug("Try to stop profiler while none is is running.");
            return false;
        }

        DateTime? currentSessionId = _traceControl.SessionStartUTC;
        if (currentSessionId is null)
        {
            throw new InvalidOperationException("Failed fetching session start time.");
        }

        if (string.IsNullOrEmpty(_currentTraceFilePath))
        {
            throw new InvalidOperationException("Current trace file path can't be null.");
        }

        try
        {
            // Notice: Stop trace session listener has to be happen before calling ITraceControl.Disable().
            // Trace control disabling will take a while. We shall not gathering anything events when disable is happening.
            _logger.LogDebug("Disabling {sessionListener}", nameof(_listener));

            List<SampleActivity>? sampleActivities = _listener?.SampleActivities?.GetActivities()?.ToList();
            _listener?.Dispose();

            // Disable the EventPipe.
            await _traceControl.DisableAsync(cancellationToken).ConfigureAwait(false);
            profilerStopped = true;
            ReleaseSemaphoreForProfiling();

            await _postStopProcessorFactory.Create().PostStopProcessAsync(new PostStopOptions(
                _currentTraceFilePath,
                currentSessionId.Value,
                stampFrontendHostUrl: _serviceProfilerContext.StampFrontendEndpointUrl,
                sampleActivities ?? Enumerable.Empty<SampleActivity>(),
                source), cancellationToken).ConfigureAwait(false);

            _logger.LogInformation(StopProfilerSucceeded);

            return true;
        }
        catch (Exception ex)
        {
            if (!profilerStopped)
            {
                _logger.LogError(ex, "Fail to disable EventPipe profiling.");
            }
            else
            {
                _logger.LogError(ex, "Unexpected error after EventPipe profiler disabled.");
            }
            throw;
        }
        finally
        {
            if (profilerStopped)
            {
                ReleaseSemaphoreForProfiling();
            }
        }
    }