System.Threading.SemaphoreSlim.WaitAsync()

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

1283 Examples 7

19 Source : CompilerHostClient.cs
with MIT License
from Azure

public async Task<CompilerResponse> GetCompilationResponse(string script, string enreplacedyType, IDictionary<string, string> references, string requestId = "")
        {
            DiagnosticsETWProvider.Instance.LogCompilerHostClientMessage(requestId, _eventSource, "Get Compilation : Waiting on semapreplaced ...");

            await _semapreplacedObject.WaitAsync();
            DiagnosticsETWProvider.Instance.LogCompilerHostClientMessage(requestId, _eventSource, "Get Compilation : Entered critical section ...");

            try
            {
                HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, $"{_compilerHostUrl}/api/compilerhost")
                {
                    Content = new StringContent(JsonConvert.SerializeObject(PrepareRequestBody(script, enreplacedyType, references)), Encoding.UTF8, "application/json")
                };

                if (!string.IsNullOrWhiteSpace(requestId))
                {
                    requestMessage.Headers.Add(HeaderConstants.RequestIdHeaderName, requestId);
                }

                if (!useCertAuth)
                {
                    string authToken = await CompilerHostTokenService.Instance.GetAuthorizationTokenAsync();
                    requestMessage.Headers.Add("Authorization", authToken);
                }
                HttpResponseMessage responseMessage = await _httpClient.SendAsync(requestMessage);

                if (!responseMessage.IsSuccessStatusCode)
                {
                    string errorResponse = await responseMessage.Content.ReadreplacedtringAsync();
                    HttpRequestException ex = new HttpRequestException($"Status Code : {responseMessage.StatusCode}, Content : {errorResponse}");
                    DiagnosticsETWProvider.Instance.LogCompilerHostClientException(requestId, _eventSource, string.Empty, ex.GetType().ToString(), ex.ToString());
                    throw ex;
                }

                return await responseMessage.Content.ReadAsAsyncCustom<CompilerResponse>();
            }
            finally
            {
                _semapreplacedObject.Release();
                DiagnosticsETWProvider.Instance.LogCompilerHostClientMessage(requestId, _eventSource, "Get Compilation : semapreplaced released.");
            }
        }

19 Source : TokenCredentialCache.cs
with MIT License
from Azure

private async Task<AccessToken> GetNewTokenAsync(
            ITrace trace)
        {
            // Use a local variable to avoid the possibility the task gets changed
            // between the null check and the await operation.
            Task<AccessToken>? currentTask = this.currentRefreshOperation;
            if (currentTask != null)
            {
                // The refresh is already occurring wait on the existing task
                return await currentTask;
            }

            try
            {
                await this.isTokenRefreshingLock.WaitAsync();

                // avoid doing the await in the semapreplaced to unblock the parallel requests
                if (this.currentRefreshOperation == null)
                {
                    // ValueTask can not be awaited multiple times
                    currentTask = this.RefreshCachedTokenWithRetryHelperAsync(trace).AsTask();
                    this.currentRefreshOperation = currentTask;
                }
                else
                {
                    currentTask = this.currentRefreshOperation;
                }
            }
            finally
            {
                this.isTokenRefreshingLock.Release();
            }

            return await currentTask;
        }

19 Source : TokenCredentialCache.cs
with MIT License
from Azure

private async ValueTask<AccessToken> RefreshCachedTokenWithRetryHelperAsync(
            ITrace trace)
        {
            try
            {
                Exception? lastException = null;
                const int totalRetryCount = 2;
                for (int retry = 0; retry < totalRetryCount; retry++)
                {
                    if (this.cancellationToken.IsCancellationRequested)
                    {
                        DefaultTrace.TraceInformation(
                            "Stop RefreshTokenWithIndefiniteRetries because cancellation is requested");

                        break;
                    }

                    using (ITrace getTokenTrace = trace.StartChild(
                        name: nameof(this.RefreshCachedTokenWithRetryHelperAsync),
                        component: TraceComponent.Authorization,
                        level: Tracing.TraceLevel.Info))
                    {
                        try
                        {
                            this.cachedAccessToken = await this.tokenCredential.GetTokenAsync(
                                requestContext: this.tokenRequestContext,
                                cancellationToken: default);

                            if (!this.cachedAccessToken.HasValue)
                            {
                                throw new ArgumentNullException("TokenCredential.GetTokenAsync returned a null token.");
                            }

                            if (this.cachedAccessToken.Value.ExpiresOn < DateTimeOffset.UtcNow)
                            {
                                throw new ArgumentOutOfRangeException($"TokenCredential.GetTokenAsync returned a token that is already expired. Current Time:{DateTime.UtcNow:O}; Token expire time:{this.cachedAccessToken.Value.ExpiresOn:O}");
                            }

                            if (!this.userDefinedBackgroundTokenCredentialRefreshInterval.HasValue)
                            {
                                double refreshIntervalInSeconds = (this.cachedAccessToken.Value.ExpiresOn - DateTimeOffset.UtcNow).TotalSeconds * DefaultBackgroundTokenCredentialRefreshIntervalPercentage;

                                // Ensure the background refresh interval is a valid range.
                                refreshIntervalInSeconds = Math.Max(refreshIntervalInSeconds, TokenCredentialCache.MinimumTimeBetweenBackgroundRefreshInterval.TotalSeconds);
                                refreshIntervalInSeconds = Math.Min(refreshIntervalInSeconds, TokenCredentialCache.MaxBackgroundRefreshInterval.TotalSeconds);
                                this.systemBackgroundTokenCredentialRefreshInterval = TimeSpan.FromSeconds(refreshIntervalInSeconds);
                            }

                            return this.cachedAccessToken.Value;
                        }
                        catch (RequestFailedException requestFailedException)
                        {
                            lastException = requestFailedException;
                            getTokenTrace.AddDatum(
                                $"RequestFailedException at {DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)}",
                                requestFailedException);

                            DefaultTrace.TraceError($"TokenCredential.GetToken() failed with RequestFailedException. scope = {string.Join(";", this.tokenRequestContext.Scopes)}, retry = {retry}, Exception = {lastException}");

                            // Don't retry on auth failures
                            if (requestFailedException.Status == (int)HttpStatusCode.Unauthorized ||
                                requestFailedException.Status == (int)HttpStatusCode.Forbidden)
                            {
                                this.cachedAccessToken = default;
                                throw;
                            }
                        }
                        catch (OperationCanceledException operationCancelled)
                        {
                            lastException = operationCancelled;
                            getTokenTrace.AddDatum(
                                $"OperationCanceledException at {DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)}",
                                operationCancelled);

                            DefaultTrace.TraceError(
                                $"TokenCredential.GetTokenAsync() failed. scope = {string.Join(";", this.tokenRequestContext.Scopes)}, retry = {retry}, Exception = {lastException}");

                            throw CosmosExceptionFactory.CreateRequestTimeoutException(
                                message: ClientResources.FailedToGetAadToken,
                                headers: new Headers()
                                {
                                    SubStatusCode = SubStatusCodes.FailedToGetAadToken,
                                },
                                innerException: lastException,
                                trace: getTokenTrace);
                        }
                        catch (Exception exception)
                        {
                            lastException = exception;
                            getTokenTrace.AddDatum(
                                $"Exception at {DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)}",
                                exception);

                            DefaultTrace.TraceError(
                                $"TokenCredential.GetTokenAsync() failed. scope = {string.Join(";", this.tokenRequestContext.Scopes)}, retry = {retry}, Exception = {lastException}");
                        }
                    }
                }

                if (lastException == null)
                {
                    throw new ArgumentException("Last exception is null.");
                }

                // The retries have been exhausted. Throw the last exception.
                throw lastException;
            }
            finally
            {
                try
                {
                    await this.isTokenRefreshingLock.WaitAsync();
                    this.currentRefreshOperation = null;
                }
                finally
                {
                    this.isTokenRefreshingLock.Release();
                }
            }
        }

19 Source : ReadManyQueryHelper.cs
with MIT License
from Azure

internal async Task<List<ResponseMessage>[]> ReadManyTaskHelperAsync(IDictionary<ParreplacedionKeyRange, List<(string, ParreplacedionKey)>> parreplacedionKeyRangeItemMap,
                                  ReadManyRequestOptions readManyRequestOptions,
                                  ITrace trace,
                                  CancellationToken cancellationToken)
        {
            SemapreplacedSlim semapreplaced = new SemapreplacedSlim(this.maxConcurrency, this.maxConcurrency);
            List<Task<List<ResponseMessage>>> tasks = new List<Task<List<ResponseMessage>>>();

            foreach (KeyValuePair<ParreplacedionKeyRange, List<(string, ParreplacedionKey)>> entry in parreplacedionKeyRangeItemMap)
            {
                // Fit MaxItemsPerQuery items in a single query to BE
                for (int startIndex = 0; startIndex < entry.Value.Count; startIndex += this.maxItemsPerQuery)
                {
                    // Only allow 'maxConcurrency' number of queries at a time
                    await semapreplaced.WaitAsync();

                    ITrace childTrace = trace.StartChild("Execute query for a parreplacedionkeyrange", TraceComponent.Query, TraceLevel.Info);
                    int indexCopy = startIndex;
                    tasks.Add(Task.Run(async () =>
                    {
                        try
                        {
                            QueryDefinition queryDefinition = ((this.parreplacedionKeySelectors.Count == 1) && (this.parreplacedionKeySelectors[0] == "[\"id\"]")) ?
                                               this.CreateReadManyQueryDefinitionForId(entry.Value, indexCopy) :
                                               this.CreateReadManyQueryDefinitionForOther(entry.Value, indexCopy);

                            return await this.GenerateStreamResponsesForParreplacedionAsync(queryDefinition,
                                                                       entry.Key,
                                                                       readManyRequestOptions,
                                                                       childTrace,
                                                                       cancellationToken);
                        }
                        finally
                        {
                            semapreplaced.Release();
                            childTrace.Dispose();
                        }
                    }));
                }
            }
            
            return await Task.WhenAll(tasks);
        }

19 Source : AsyncCacheTest.cs
with MIT License
from Azure

[TestMethod]
        public async Task TestFailureOnOneThreadDoesNotFailAnother()
        {
            AsyncCache<int, int> cache = new AsyncCache<int, int>();
            SemapreplacedSlim resetEventSlim = new SemapreplacedSlim(0, 1);

            Func<Task<int>> generatorFunc1 = () => Task<int>.Run(async () =>
            {
                await resetEventSlim.WaitAsync();
                return this.GenerateIntFuncThatThrows();
            });

            Func<Task<int>> generatorFunc2 = () => Task.Run(() =>
            {
                return 2;
            });

            // set up two threads that are concurrently updating the async cache for the same key.
            // the only difference is that one thread preplacedes in a cancellation token
            // and the other does not.
            Task<int> getTask1 = cache.GetAsync(key: 1, obsoleteValue: -1, singleValueInitFunc: generatorFunc1, cancellationToken: CancellationToken.None);

            Task<int> getTask2 = cache.GetAsync(key: 1, obsoleteValue: -1, singleValueInitFunc: generatorFunc2, cancellationToken: CancellationToken.None);

            // replacedert that the tasks haven't completed.
            replacedert.IsFalse(getTask2.IsCompleted);
            replacedert.IsFalse(getTask1.IsCompleted);

            // release a thread that causes the first to throw.
            resetEventSlim.Release();

            // neither task is complete at this point.
            replacedert.IsFalse(getTask2.IsCompleted);
            replacedert.IsFalse(getTask1.IsCompleted);

            try
            {
                await getTask1;
                replacedert.Fail("Should fail because of exception.");
            }
            catch (Exception e)
            {
                replacedert.AreEqual(typeof(InvalidOperationException), e.GetType(), e.Message);
            }

            // task 2 should not fail because task 1 got cancelled.
            int getTaskResult2 = await getTask2;
            replacedert.AreEqual(2, getTaskResult2);
        }

19 Source : UsableSemaphoreWrapperTests.cs
with MIT License
from Azure

[TestMethod]
        public async Task NotDisposedAfterUsing()
        {
            SemapreplacedSlim semapreplaced = new SemapreplacedSlim(1, 1);
            using(await semapreplaced.UsingWaitAsync(NoOpTrace.Singleton, default))
            {
                ;
            }

            // Normal flow
            await semapreplaced.WaitAsync();
            semapreplaced.Release();

            semapreplaced.Dispose();
        }

19 Source : QueryScenario.cs
with MIT License
from Azure

private async static Task ExecuteQueryWithContinuationAndGatherResultsAsync(CTLConfig config,
            CosmosClient cosmosClient,
            ILogger logger,
            IMetrics metrics,
            string loggingContextIdentifier,
            CancellationToken cancellationToken,
            string queryText,
            string queryName,
            long expectedResults,
            SemapreplacedSlim concurrencyControlSemapreplaced)
        {
            Stopwatch stopWatch = Stopwatch.StartNew();

            GaugeOptions doreplacedentGauge = new GaugeOptions
            {
                Name = $"#{queryName} Query with CT received doreplacedents",
                MeasurementUnit = Unit.Items,
                Context = loggingContextIdentifier
            };

            Container container = cosmosClient.GetContainer(config.Database, config.Collection);
            while (stopWatch.Elapsed <= config.RunningTimeDurationAsTimespan
                && !cancellationToken.IsCancellationRequested)
            {
                // To really debug what happened on the query, having a list of all continuations would be useful.
                List<string> allContinuations = new List<string>();
                long doreplacedentTotal = 0;
                string continuation;
                await concurrencyControlSemapreplaced.WaitAsync();
                FeedIterator<Dictionary<string, string>> query = container.GereplacedemQueryIterator<Dictionary<string, string>>(queryText);
                try
                {
                    while (query.HasMoreResults)
                    {
                        FeedResponse<Dictionary<string, string>> response = await query.ReadNextAsync();
                        doreplacedentTotal += response.Count;
                        continuation = response.ContinuationToken;
                        allContinuations.Add(continuation);
                        if (continuation != null)
                        {
                            // Use continuation to paginate on the query instead of draining just the initial query
                            // This validates that we can indeed move forward with the continuation
                            query.Dispose();
                            query = container.GereplacedemQueryIterator<Dictionary<string, string>>(queryText, continuation);
                        }

                        Utils.LogDiagnostics(
                            logger: logger,
                            operationName: queryName,
                            timerContextLatency: response.Diagnostics.GetClientElapsedTime(),
                            config: config,
                            cosmosDiagnostics: response.Diagnostics);
                    }

                    query.Dispose();

                    metrics.Measure.Gauge.SetValue(doreplacedentGauge, doreplacedentTotal);

                    if (expectedResults > 0 && expectedResults != doreplacedentTotal)
                    {
                        StringBuilder errorDetail = new StringBuilder();
                        errorDetail.AppendLine($"{queryName} Query with CT expected to read {expectedResults} but got {doreplacedentTotal}");
                        foreach (string c in allContinuations)
                        {
                            errorDetail.AppendLine($"Continuation: {c}");
                        }

                        Utils.LogError(logger, loggingContextIdentifier, errorDetail.ToString());
                    }
                }
                catch (Exception ex)
                {
                    metrics.Measure.Gauge.SetValue(doreplacedentGauge, doreplacedentTotal);

                    StringBuilder errorDetail = new StringBuilder();
                    errorDetail.AppendLine($"{queryName} Query with CT failure while looping through query.");
                    foreach (string c in allContinuations)
                    {
                        errorDetail.AppendLine($"Continuation: {c}");
                    }

                    Utils.LogError(logger, loggingContextIdentifier, ex, errorDetail.ToString());
                }
                finally
                {
                    concurrencyControlSemapreplaced.Release();
                }
            }

            stopWatch.Stop();
        }

19 Source : QueryScenario.cs
with MIT License
from Azure

private async static Task ExecuteQueryAndGatherResultsAsync(CTLConfig config,
            CosmosClient cosmosClient,
            ILogger logger,
            IMetrics metrics,
            string loggingContextIdentifier,
            CancellationToken cancellationToken,
            string queryText,
            string queryName,
            long expectedResults,
            SemapreplacedSlim concurrencyControlSemapreplaced)
        {
            Stopwatch stopWatch = Stopwatch.StartNew();

            GaugeOptions doreplacedentGauge = new GaugeOptions
            {
                Name = $"#{queryName} Query received doreplacedents",
                MeasurementUnit = Unit.Items,
                Context = loggingContextIdentifier
            };

            Container container = cosmosClient.GetContainer(config.Database, config.Collection);
            while (stopWatch.Elapsed <= config.RunningTimeDurationAsTimespan
                && !cancellationToken.IsCancellationRequested)
            {
                long doreplacedentTotal = 0;
                string continuation = null;
                await concurrencyControlSemapreplaced.WaitAsync();
                using FeedIterator<Dictionary<string, string>> query = container.GereplacedemQueryIterator<Dictionary<string, string>>(queryText);
                try
                {
                    while (query.HasMoreResults)
                    {
                        FeedResponse<Dictionary<string, string>> response = await query.ReadNextAsync();
                        doreplacedentTotal += response.Count;
                        continuation = response.ContinuationToken;

                        Utils.LogDiagnostics(
                            logger: logger,
                            operationName: queryName,
                            timerContextLatency: response.Diagnostics.GetClientElapsedTime(),
                            config: config,
                            cosmosDiagnostics: response.Diagnostics);
                    }

                    metrics.Measure.Gauge.SetValue(doreplacedentGauge, doreplacedentTotal);

                    if (expectedResults > 0 && expectedResults != doreplacedentTotal)
                    {
                        StringBuilder errorDetail = new StringBuilder();
                        errorDetail.AppendLine($"{queryName} Query expected to read {expectedResults} but got {doreplacedentTotal}");
                        errorDetail.AppendLine($"Last continuation: {continuation}");

                        Utils.LogError(logger, loggingContextIdentifier, errorDetail.ToString());
                    }
                }
                catch (CosmosException ce) when (ce.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
                {
                    //Logging 429s is not relevant
                }
                catch (Exception ex)
                {
                    metrics.Measure.Gauge.SetValue(doreplacedentGauge, doreplacedentTotal);

                    StringBuilder errorDetail = new StringBuilder();
                    errorDetail.AppendLine($"{queryName} Query failure while looping through query.");
                    errorDetail.AppendLine($"Last continuation: {continuation}");

                    Utils.LogError(logger, loggingContextIdentifier, ex, errorDetail.ToString());
                }
                finally
                {
                    concurrencyControlSemapreplaced.Release();
                }
            }

            stopWatch.Stop();
        }

19 Source : AsyncLock.cs
with MIT License
from Azure

public async Task<Releaser> AcquireAsync()
        {
            await this.semapreplaced.WaitAsync();
            return new Releaser(this);
        }

19 Source : MessagingStream.cs
with MIT License
from Azure

private async Task WriteImplAsync(StreamingMessage message)
        {
            try
            {
                await _semapreplacedSlim.WaitAsync();
                await _call.RequestStream.WriteAsync(message);
            }
            finally
            {
                _semapreplacedSlim.Release();
            }
        }

19 Source : MSITokenProvider.cs
with MIT License
from Azure

private async Task<MSIToken> GetTokenFromIMDSEndpointAsync(string resource, CancellationToken cancellationToken)
        {
            // First hit cache
            //
            if (cache.TryGetValue(resource, out MSIToken token) == true && !token.IsExpired)
            {
                return token;
            }

            // if cache miss then retrieve from IMDS endpoint with retry
            //
            await semapreplacedSlim.WaitAsync();
            try
            {
                // Try hit cache once again in case another thread already updated the cache while this thread was waiting
                //
                if (cache.TryGetValue(resource, out token) == true && !token.IsExpired)
                {
                    return token;
                }
                else
                {
                    token = await this.RetrieveTokenFromIMDSWithRetryAsync(resource, cancellationToken);
                    cache.AddOrUpdate(resource, token, (key, oldValue) => token);
                    return token;
                }
            }
            finally
            {
                semapreplacedSlim.Release();
            }
        }

19 Source : AzureDevOpsService.cs
with MIT License
from Azure

private async Task<T> GetClientAsync<T>() 
            where T : VssHttpClientBase
        {
            var type = typeof(T);
            T result;
            await clientCacheSemapreplaced.WaitAsync();
            if (clientCache.ContainsKey(type))
            {
                
                result = (T)clientCache[type];
            }
            else
            {
                result = await connection.GetClientAsync<T>();
                clientCache.Add(type, result);
            }

            clientCacheSemapreplaced.Release();
            return result;
        }

19 Source : ServiceConnectionBase.cs
with MIT License
from Azure

public async Task StartAsync(string target = null)
        {
            if (Interlocked.CompareExchange(ref _started, 1, 0) != 0)
            {
                throw new InvalidOperationException("Connection already started!");
            }

            Status = ServiceConnectionStatus.Connecting;

            var connection = await EstablishConnectionAsync(target);
            if (connection != null)
            {
                _connectionContext = connection;
                Status = ServiceConnectionStatus.Connected;
                _serviceConnectionStartTcs.TrySetResult(true);
                try
                {
                    TimerAwaitable syncTimer = null;
                    try
                    {
                        if (HubEndpoint != null && HubEndpoint.AccessKey is AadAccessKey aadKey)
                        {
                            syncTimer = new TimerAwaitable(TimeSpan.Zero, DefaultSyncAzureIdenreplacedyInterval);
                            _ = UpdateAzureIdenreplacedyAsync(aadKey, syncTimer);
                        }
                        await ProcessIncomingAsync(connection);
                    }
                    finally
                    {
                        syncTimer?.Stop();
                        // when ProcessIncoming completes, clean up the connection

                        // TODO: Never cleanup connections unless Service asks us to do that
                        // Current implementation is based on replacedumption that Service will drop clients
                        // if server connection fails.
                        await CleanupClientConnections();
                    }
                }
                catch (Exception ex)
                {
                    Log.ConnectionDropped(Logger, HubEndpoint.ToString(), ConnectionId, ex);
                }
                finally
                {
                    // wait until all the connections are cleaned up to close the outgoing pipe
                    // mark the status as Disconnected so that no one will write to this connection anymore
                    // Don't allow write anymore when the connection is disconnected
                    Status = ServiceConnectionStatus.Disconnected;

                    await _writeLock.WaitAsync();
                    try
                    {
                        // close the underlying connection
                        await DisposeConnection(connection);
                    }
                    finally
                    {
                        _writeLock.Release();
                    }
                }
            }
            else
            {
                Status = ServiceConnectionStatus.Disconnected;
                _serviceConnectionStartTcs.TrySetResult(false);
            }
        }

19 Source : ServiceConnectionBase.cs
with MIT License
from Azure

protected virtual async Task<bool> SafeWriteAsync(ServiceMessage serviceMessage)
        {
            if (!string.IsNullOrEmpty(_errorMessage) || Status != ServiceConnectionStatus.Connected)
            {
                return false;
            }

            await _writeLock.WaitAsync().ConfigureAwait(false);

            if (Status != ServiceConnectionStatus.Connected)
            {
                // Make sure not write messages to the connection when it is no longer connected
                _writeLock.Release();
                return false;
            }
            try
            {
                // Write the service protocol message
                ServiceProtocol.WriteMessage(serviceMessage, _connectionContext.Transport.Output);
                await _connectionContext.Transport.Output.FlushAsync().ConfigureAwait(false);
                return true;
            }
            catch (Exception ex)
            {
                // We always mark the connection as Disconnected before dispose the underlying http connection
                // So in theory this log should never trigger
                Log.FailedToWrite(Logger, (serviceMessage as IMessageWithTracingId)?.TracingId, ConnectionId, ex);
                return false;
            }
            finally
            {
                _writeLock.Release();
            }
        }

19 Source : Worker.cs
with MIT License
from Azure

public async Task StartAsync() {
            await _lock.WaitAsync();
            try {
                if (_cts != null) {
                    _logger.Warning("Worker already running");
                    return;
                }

                _cts = new CancellationTokenSource();
                _heartbeatTimer.Change(TimeSpan.Zero, Timeout.InfiniteTimeSpan);

                _logger.Information("Worker {WorkerId}: {@Capabilities}",
                    WorkerId, _agentConfigProvider.Config.Capabilities);
                _worker = Task.Run(() => RunAsync(_cts.Token));
            }
            finally {
                _lock.Release();
            }
        }

19 Source : Worker.cs
with MIT License
from Azure

public async Task StopAsync() {
            await _lock.WaitAsync();
            try {
                if (_cts == null) {
                    return;
                }

                _logger.Information("Stopping worker...");
                _heartbeatTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);

                // Inform services, that this worker has stopped working, so orchestrator can rereplacedign job
                if (_jobProcess != null) {
                    _jobProcess.Status = WorkerStatus.Stopped;
                    await SendHeartbeatWithoutResetTimer(); // need to be send before cancel the CancellationToken
                }

                // Stop worker
                _cts.Cancel();
                await _worker;
                _worker = null;

                System.Diagnostics.Debug.replacedert(_jobProcess == null);
                _logger.Information("Worker stopped.");
            }
            catch (OperationCanceledException) { }
            catch (Exception e) {
                _logger.Error(e, "Stopping worker failed.");
            }
            finally {
                _cts?.Dispose();
                _cts = null;
                _lock.Release();
            }
        }

19 Source : EventBusHost.cs
with MIT License
from Azure

public async Task StartAsync() {
            await _lock.WaitAsync();
            try {
                if (_handlers.Any(h => h.Value != null)) {
                    _logger.Debug("Event bus host already running.");
                    return;
                }
                var register = _client.GetType().GetMethod(nameof(IEventBus.RegisterAsync));
                foreach (var handler in _handlers.Keys.ToList()) {
                    var type = handler.GetType();
                    foreach (var itf in type.GetInterfaces()) {
                        try {
                            var eventType = itf.GetGenericArguments().FirstOrDefault();
                            if (eventType == null) {
                                continue;
                            }
                            var method = register.MakeGenericMethod(eventType);
                            _logger.Debug("Starting Event bus bridge for {type}...",
                                type.Name);
                            var token = await (Task<string>)method.Invoke(
                                _client, new object[] { handler });
                            _handlers[handler] = token; // Store token to unregister
                            _logger.Information("Event bus bridge for {type} started.",
                                type.Name);
                        }
                        catch (Exception ex) {
                            _logger.Error(ex, "Failed to start Event bus host for {type}.",
                                type.Name);
                            throw;
                        }
                    }
                }
                _logger.Information("Event bus host running.");
            }
            finally {
                _lock.Release();
            }
        }

19 Source : EventBusHost.cs
with MIT License
from Azure

public async Task StopAsync() {
            await _lock.WaitAsync();
            try {
                foreach (var token in _handlers.Where(x => x.Value != null).ToList()) {
                    try {
                        // Unregister using stored token
                        await _client.UnregisterAsync(token.Value);
                        _handlers[token.Key] = null;
                    }
                    catch (Exception ex) {
                        _logger.Error(ex, "Failed to stop Event bus host using token {token}.",
                            token);
                        throw;
                    }
                }
                _handlers.Clear();
                _logger.Information("Event bus host stopped.");
            }
            finally {
                _lock.Release();
            }
        }

19 Source : SignalRHubClient.cs
with MIT License
from Azure

public async Task<ICallbackRegistrar> GetHubAsync(string endpointUrl,
            string resourceId) {
            if (_disposed) {
                throw new ObjectDisposedException(nameof(SignalRHubClient));
            }
            if (string.IsNullOrEmpty(endpointUrl)) {
                throw new ArgumentNullException(nameof(endpointUrl));
            }
            await _lock.WaitAsync();
            try {
                var lookup = endpointUrl;
                if (!string.IsNullOrEmpty(resourceId)) {
                    lookup += resourceId;
                }
                if (!_clients.TryGetValue(lookup, out var client) ||
                    client.ConnectionId == null) {
                    if (client != null) {
                        await client.DisposeAsync();
                        _clients.Remove(lookup);
                    }
                    client = await SignalRClientRegistrar.CreateAsync(_config,
                        endpointUrl, _logger, resourceId, _provider, _jsonSettings);
                    _clients.Add(lookup, client);
                }
                return client;
            }
            finally {
                _lock.Release();
            }
        }

19 Source : ModuleHost.cs
with MIT License
from Azure

public async Task StartAsync(string type, string siteId, string productInfo,
            string version, IProcessControl reset) {
            if (Client == null) {
                try {
                    await _lock.WaitAsync();
                    if (Client == null) {
                        // Create client
                        _logger.Debug("Starting Module Host...");
                        Client = await _factory.CreateAsync(productInfo + "_" + version, reset);
                        DeviceId = _factory.DeviceId;
                        ModuleId = _factory.ModuleId;
                        Gateway = _factory.Gateway;
                        // Register callback to be called when a method request is received
                        await Client.SetMethodDefaultHandlerAsync((request, _) =>
                            _router.InvokeMethodAsync(request), null);

                        await InitializeTwinAsync();

                        // Register callback to be called when settings change ...
                        await Client.SetDesiredPropertyUpdateCallbackAsync(
                            (settings, _) => ProcessSettingsAsync(settings), null);

                        // Report type of service, chosen site, and connection state
                        var twinSettings = new TwinCollection {
                            [TwinProperty.Type] = type
                        };

                        // Set site if provided
                        if (string.IsNullOrEmpty(SiteId)) {
                            SiteId = siteId;
                            twinSettings[TwinProperty.SiteId] = SiteId;
                        }

                        // Set version information
                        twinSettings[TwinProperty.Version] = version;
                        await Client.UpdateReportedPropertiesAsync(twinSettings);

                        // Done...
                        kModuleStart.WithLabels(DeviceId ?? "", ModuleId ?? "",
                            _moduleGuid, version,
                            DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK",
                            CultureInfo.InvariantCulture)).Set(1);
                        _logger.Information("Module Host started.");
                        return;
                    }
                }
                catch (Exception) {
                    kModuleStart.WithLabels(DeviceId ?? "", ModuleId ?? "",
                        _moduleGuid, version,
                        DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK",
                        CultureInfo.InvariantCulture)).Set(0);
                    _logger.Error("Module Host failed to start.");
                    Client?.Dispose();
                    Client = null;
                    _reported?.Clear();
                    DeviceId = null;
                    ModuleId = null;
                    SiteId = null;
                    Gateway = null;
                    throw;
                }
                finally {
                    _lock.Release();
                }
            }
            throw new InvalidOperationException("Already started");
        }

19 Source : ModuleHost.cs
with MIT License
from Azure

public async Task RefreshAsync() {
            try {
                await _lock.WaitAsync();
                if (Client != null) {
                    var twin = await Client.GetTwinAsync();
                    _reported.Clear();
                    foreach (KeyValuePair<string, dynamic> property in twin.Properties.Reported) {
                        _reported.AddOrUpdate(property.Key,
                            (VariantValue)_serializer.FromObject(property.Value));
                    }
                    var reported = new Dictionary<string, VariantValue>();
                    await ReportControllerStateAsync(twin, reported);
                }
            }
            finally {
                _lock.Release();
            }
        }

19 Source : ModuleHost.cs
with MIT License
from Azure

public async Task SendEventAsync(IEnumerable<byte[]> batch, string contentType,
            string eventSchema, string contentEncoding) {
            try {
                await _lock.WaitAsync();
                if (Client != null) {
                    var messages = batch
                        .Select(ev =>
                             CreateMessage(ev, contentEncoding, contentType, eventSchema,
                                DeviceId, ModuleId))
                        .ToList();
                    try {
                        await Client.SendEventBatchAsync(messages);
                    }
                    finally {
                        messages.ForEach(m => m?.Dispose());
                    }
                }
            }
            finally {
                _lock.Release();
            }
        }

19 Source : ModuleHost.cs
with MIT License
from Azure

public async Task SendEventAsync(byte[] data, string contentType, string eventSchema,
            string contentEncoding) {
            try {
                await _lock.WaitAsync();
                if (Client != null) {
                    using (var msg = CreateMessage(data, contentEncoding, contentType,
                        eventSchema, DeviceId, ModuleId)) {
                        await Client.SendEventAsync(msg);
                    }
                }
            }
            finally {
                _lock.Release();
            }
        }

19 Source : ModuleHost.cs
with MIT License
from Azure

public async Task ReportAsync(IEnumerable<KeyValuePair<string, VariantValue>> properties) {
            try {
                await _lock.WaitAsync();
                if (Client != null) {
                    var collection = new TwinCollection();
                    foreach (var property in properties) {
                        collection[property.Key] = property.Value?.ConvertTo<object>();
                    }
                    await Client.UpdateReportedPropertiesAsync(collection);
                    foreach (var property in properties) {
                        _reported.Remove(property.Key);
                        _reported.Add(property.Key, property.Value);
                    }
                }
            }
            finally {
                _lock.Release();
            }
        }

19 Source : ModuleHost.cs
with MIT License
from Azure

public async Task ReportAsync(string propertyId, VariantValue value) {
            try {
                await _lock.WaitAsync();
                if (Client != null) {
                    var collection = new TwinCollection {
                        [propertyId] = value?.ConvertTo<object>()
                    };
                    await Client.UpdateReportedPropertiesAsync(collection);
                    _reported.Remove(propertyId);
                    _reported.Add(propertyId, value);
                }
            }
            finally {
                _lock.Release();
            }
        }

19 Source : ModuleHost.cs
with MIT License
from Azure

private async Task ProcessSettingsAsync(TwinCollection settings) {
            if (settings.Count > 0) {
                try {
                    await _lock.WaitAsync();

                    // Patch existing reported properties
                    var desired = new Dictionary<string, VariantValue>();
                    var reporting = new Dictionary<string, VariantValue>();

                    foreach (KeyValuePair<string, dynamic> property in settings) {
                        var value = (VariantValue)_serializer.FromObject(property.Value);
                        if (!ProcessEdgeHostSettings(property.Key, value, reporting)) {
                            desired.AddOrUpdate(property.Key, value);
                        }
                    }

                    if (reporting != null && reporting.Count != 0) {
                        var collection = new TwinCollection();
                        foreach (var item in reporting) {
                            collection[item.Key] = item.Value?.ConvertTo<object>();
                        }
                        await Client.UpdateReportedPropertiesAsync(collection);
                        _logger.Debug("Internal state updated...", reporting);
                    }

                    // Any controller properties left?
                    if (desired.Count == 0) {
                        return;
                    }

                    _logger.Debug("Processing new settings...");
                    var reported = await _settings.ProcessSettingsAsync(desired);

                    if (reported != null && reported.Count != 0) {
                        _logger.Debug("Reporting setting results...");
                        var collection = new TwinCollection();
                        foreach (var item in reported) {
                            collection[item.Key] = item.Value?.ConvertTo<object>();
                        }
                        await Client.UpdateReportedPropertiesAsync(collection);
                        foreach (var item in reported) {
                            _reported.AddOrUpdate(item.Key, item.Value);
                        }
                    }
                    _logger.Information("New settings processed.");
                }
                finally {
                    _lock.Release();
                }
            }
        }

19 Source : ServiceBusClientFactory.cs
with MIT License
from Azure

public async Task<ISubscriptionClient> CreateOrGetSubscriptionClientAsync(
            Func<Message, CancellationToken, Task> handler,
            Func<ExceptionReceivedEventArgs, Task> exceptionReceivedHandler,
            string name, string topic) {
            topic = GetEnreplacedyName(topic);
            if (string.IsNullOrEmpty(name)) {
                name = Dns.GetHostName();
            }
            await _subscriptionLock.WaitAsync();
            try {
                var key = $"{topic}/subscriptions/{name}";
                if (!_subscriptionClients.TryGetValue(key, out var client) ||
                    client.IsClosedOrClosing) {
                    client = await NewSubscriptionClientAsync(topic, name);
                    _subscriptionClients.Add(key, client);

                    //
                    // TODO: Should also check whether the handlers are different
                    // and close/create new subscription handler...
                    //
                    client.RegisterMessageHandler(handler,
                        new MessageHandlerOptions(exceptionReceivedHandler) {
                            MaxConcurrentCalls = 2,
                            MaxAutoRenewDuration = TimeSpan.FromMinutes(1),
                            AutoComplete = false
                        });
                }
                return client;
            }
            finally {
                _subscriptionLock.Release();
            }
        }

19 Source : SignalRHubClient.cs
with MIT License
from Azure

public async ValueTask DisposeAsync() {
            if (_disposed) {
                return;
            }
            await _lock.WaitAsync();
            try {
                foreach (var client in _clients.Values) {
                    await client.DisposeAsync();
                }
                _clients.Clear();
            }
            finally {
                _lock.Release();
                _disposed = true;
            }
            _lock.Dispose();
        }

19 Source : SignalRHubClientHost.cs
with MIT License
from Azure

public async Task StartAsync() {
            await _lock.WaitAsync();
            try {
                if (_started) {
                    _logger.Debug("SignalR client host already running.");
                    return;
                }
                _logger.Debug("Starting SignalR client host...");
                _started = true;
                _connection = await OpenAsync();
                _logger.Information("SignalR client host started.");
            }
            catch (Exception ex) {
                _started = false;
                _logger.Error(ex, "Error starting SignalR client host.");
                throw;
            }
            finally {
                _lock.Release();
            }
        }

19 Source : SignalRHubClientHost.cs
with MIT License
from Azure

public async Task StopAsync() {
            await _lock.WaitAsync();
            try {
                if (!_started) {
                    return;
                }
                _started = false;
                _logger.Debug("Stopping SignalR client host...");
                await DisposeAsync(_connection);
                _connection = null;
                _logger.Information("SignalR client host stopped.");
            }
            catch (Exception ex) {
                _logger.Warning(ex, "Error stopping SignalR client host.");
            }
            finally {
                _lock.Release();
            }
        }

19 Source : ModuleHost.cs
with MIT License
from Azure

public async Task StopAsync() {
            if (Client != null) {
                try {
                    await _lock.WaitAsync();
                    if (Client != null) {
                        _logger.Information("Stopping Module Host...");
                        try {
                            await Client.CloseAsync();
                        }
                        catch (OperationCanceledException) { }
                        catch (IotHubCommunicationException) { }
                        catch (DeviceNotFoundException) { }
                        catch (UnauthorizedException) { }
                        catch (Exception se) {
                            _logger.Error(se, "Module Host not cleanly disconnected.");
                        }
                    }
                    _logger.Information("Module Host stopped.");
                }
                catch (Exception ce) {
                    _logger.Error(ce, "Module Host stopping caused exception.");
                }
                finally {
                    kModuleStart.WithLabels(DeviceId ?? "", ModuleId ?? "", _moduleGuid, "",
                        DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK",
                        CultureInfo.InvariantCulture)).Set(0);
                    Client?.Dispose();
                    Client = null;
                    _reported?.Clear();
                    DeviceId = null;
                    ModuleId = null;
                    SiteId = null;
                    Gateway = null;
                    _lock.Release();
                }
            }
        }

19 Source : SettingsRouter.cs
with MIT License
from Azure

public async Task<IDictionary<string, VariantValue>> ProcessSettingsAsync(
            IDictionary<string, VariantValue> settings) {
            var controllers = new List<Controller>();

            // Set all properties
            foreach (var setting in settings) {
                if (!TryGetInvoker(setting.Key, out var invoker)) {
                    _logger.Error("Setting {key}/{value} unsupported",
                        setting.Key, setting.Value.ToJson());
                }
                else {
                    try {
                        var controller = invoker.Set(setting.Key, setting.Value);
                        if (controller != null && !controllers.Contains(controller)) {
                            controllers.Add(controller); // To apply only affected controllers
                        }
                    }
                    catch (Exception ex) {
                        _logger.Error(ex, "Error processing setting {key}/{value}",
                            setting.Key, setting.Value.ToJson());
                    }
                }
            }

            // Apply settings on all affected controllers and return reported
            var reported = new Dictionary<string, VariantValue>();
            if (controllers.Any()) {
                var sw = Stopwatch.StartNew();
                await _lock.WaitAsync();
                try {
                    await Task.WhenAll(controllers.Select(c => c.SafeApplyAsync()));
                    var invokers = controllers.SelectMany(c => c.Invokers).Distinct();
                    CollectSettingsFromControllers(reported, invokers);
                    _logger.Debug("Applying new settings took {elapsed}...", sw.Elapsed);
                }
                finally {
                    _lock.Release();
                }
            }
            return reported;
        }

19 Source : SettingsRouter.cs
with MIT License
from Azure

public async Task<IDictionary<string, VariantValue>> GetSettingsStateAsync() {
            await _lock.WaitAsync();
            try {
                var reported = new Dictionary<string, VariantValue>();
                CollectSettingsFromControllers(reported, _calltable.Values);
                return reported;
            }
            finally {
                _lock.Release();
            }
        }

19 Source : EventProcessorHost.cs
with MIT License
from Azure

public async Task StartAsync() {
            await _lock.WaitAsync();
            try {
                if (_host != null) {
                    _logger.Debug("Event processor host already running.");
                    return;
                }

                _logger.Debug("Starting event processor host...");
                var consumerGroup = _hub.ConsumerGroup;
                if (string.IsNullOrEmpty(consumerGroup)) {
                    consumerGroup = "$default";
                }
                _logger.Information("Using Consumer Group: \"{consumerGroup}\"", consumerGroup);
                if (_lease != null && _checkpoint != null) {
                    _host = new EventHubs.Processor.EventProcessorHost(
                        $"host-{Guid.NewGuid()}", _hub.EventHubPath, consumerGroup,
                        GetEventHubConnectionString(), _checkpoint, _lease);
                }
                else {
                    var blobConnectionString = _config.GetStorageConnString();
                    if (!string.IsNullOrEmpty(blobConnectionString)) {
                        _host = new EventHubs.Processor.EventProcessorHost(
                            _hub.EventHubPath, consumerGroup, GetEventHubConnectionString(),
                            blobConnectionString,
                            !string.IsNullOrEmpty(_config.LeaseContainerName) ?
                                _config.LeaseContainerName : _hub.EventHubPath.ToSha1Hash());
                    }
                    else {
                        throw new InvalidConfigurationException(
                            "Invalid checkpointing configuration. No storage configured " +
                            "or checkpoint manager/lease manager implementation injected.");
                    }
                }
                await _host.RegisterEventProcessorFactoryAsync(
                    _factory, new EventProcessorOptions {
                        InitialOffsetProvider = s => _config.InitialReadFromEnd ?
                            EventPosition.FromEnqueuedTime(DateTime.UtcNow) :
                            EventPosition.FromStart(),
                        MaxBatchSize = _config.ReceiveBatchSize,
                        ReceiveTimeout = _config.ReceiveTimeout,
                        InvokeProcessorAfterReceiveTimeout = true
                    });
                _logger.Information("Event processor host started.");
            }
            catch (Exception ex) {
                _logger.Error(ex, "Error starting event processor host.");
                _host = null;
                throw;
            }
            finally {
                _lock.Release();
            }
        }

19 Source : EventProcessorHost.cs
with MIT License
from Azure

public async Task StopAsync() {
            await _lock.WaitAsync();
            try {
                if (_host != null) {
                    _logger.Debug("Stopping event processor host...");
                    await _host.UnregisterEventProcessorAsync();
                    _host = null;
                    _logger.Information("Event processor host stopped.");
                }
            }
            catch (Exception ex) {
                _logger.Warning(ex, "Error stopping event processor host");
                _host = null;
            }
            finally {
                _lock.Release();
            }
        }

19 Source : ServiceBusClientFactory.cs
with MIT License
from Azure

public async Task<ITopicClient> CreateOrGetTopicClientAsync(string topic) {
            topic = GetEnreplacedyName(topic);
            await _topicLock.WaitAsync();
            try {
                if (!_topicClients.TryGetValue(topic, out var client) ||
                    client.IsClosedOrClosing) {
                    client = await NewTopicClientAsync(topic);
                    _topicClients.Add(topic, client);
                }
                return client;
            }
            finally {
                _topicLock.Release();
            }
        }

19 Source : ServiceBusClientFactory.cs
with MIT License
from Azure

public async Task<IQueueClient> CreateOrGetGetQueueClientAsync(string queue) {
            queue = GetEnreplacedyName(queue);
            await _queueLock.WaitAsync();
            try {
                if (!_queueClients.TryGetValue(queue, out var client) ||
                    client.IsClosedOrClosing) {
                    client = await NewQueueClientAsync(queue);
                    _queueClients.Add(queue, client);
                }
                return client;
            }
            finally {
                _queueLock.Release();
            }
        }

19 Source : ServiceBusClientFactory.cs
with MIT License
from Azure

private static async Task CloseAllAsync<T>(SemapreplacedSlim clientLock,
            Dictionary<string, T> clients) where T : IClientEnreplacedy {
            await clientLock.WaitAsync();
            try {
                foreach (var client in clients.Values) {
                    await Try.Async(() => client.CloseAsync());
                }
                clients.Clear();
            }
            finally {
                clientLock.Release();
            }
        }

19 Source : ServiceBusEventBus.cs
with MIT License
from Azure

public async Task CloseAsync() {
            await _lock.WaitAsync();
            try {
                foreach (var handlers in _handlers) {
                    var eventName = handlers.Key;
                    try {
                        await _subscriptionClient.RemoveRuleAsync(eventName);
                    }
                    catch (MessagingEnreplacedyNotFoundException) {
                        _logger.Warning("The messaging enreplacedy {eventName} could not be found.",
                            eventName);
                    }
                }
                _handlers.Clear();
                if (_subscriptionClient.IsClosedOrClosing) {
                    return;
                }
                await _subscriptionClient.CloseAsync();
            }
            finally {
                _lock.Release();
            }
        }

19 Source : ServiceBusEventBus.cs
with MIT License
from Azure

public async Task<string> RegisterAsync<T>(IEventHandler<T> handler) {
            var eventName = typeof(T).GetMoniker();
            await _lock.WaitAsync();
            try {
                if (!_handlers.TryGetValue(eventName, out var handlers)) {
                    try {
                        await _subscriptionClient.AddRuleAsync(new RuleDescription {
                            Filter = new CorrelationFilter { Label = eventName },
                            Name = eventName
                        });
                    }
                    catch (ServiceBusException ex) {
                        if (ex.Message.Contains("already exists")) {
                            _logger.Debug("The messaging enreplacedy {eventName} already exists.",
                                eventName);
                        }
                        else {
                            throw;
                        }
                    }
                    handlers = new Dictionary<string, Subscription>();
                    _handlers.Add(eventName, handlers);
                }
                var token = Guid.NewGuid().ToString();
                handlers.Add(token, new Subscription {
                    HandleAsync = e => handler.HandleAsync((T)e),
                    Type = typeof(T)
                });
                return token;
            }
            finally {
                _lock.Release();
            }
        }

19 Source : ServiceBusEventBus.cs
with MIT License
from Azure

public async Task UnregisterAsync(string token) {
            await _lock.WaitAsync();
            try {
                string eventName = null;
                foreach (var subscriptions in _handlers) {
                    eventName = subscriptions.Key;
                    if (subscriptions.Value.TryGetValue(token, out var subscription)) {

                        // Remove handler
                        subscriptions.Value.Remove(token);
                        if (subscriptions.Value.Count != 0) {
                            eventName = null;
                            break;
                        }
                    }
                }
                if (string.IsNullOrEmpty(eventName)) {
                    return; // No more action
                }
                try {
                    await _subscriptionClient.RemoveRuleAsync(eventName);
                }
                catch (ServiceBusException) {
                    _logger.Warning("The messaging enreplacedy {eventName} does not exist.",
                        eventName);
                    // TODO: throw?
                }
                _handlers.Remove(eventName);
            }
            finally {
                _lock.Release();
            }
        }

19 Source : ServiceBusEventBus.cs
with MIT License
from Azure

private async Task ProcessEventAsync(Message message, CancellationToken token) {
            IEnumerable<Subscription> subscriptions = null;
            await _lock.WaitAsync();
            try {
                if (!_handlers.TryGetValue(message.Label, out var handlers)) {
                    return;
                }
                subscriptions = handlers.Values.ToList();
            }
            finally {
                _lock.Release();
            }
            foreach (var handler in subscriptions) {
                // Do for now every time to preplaced brand new objects
                var evt = _serializer.Deserialize(message.Body, handler.Type);
                await handler.HandleAsync(evt);
                _logger.Verbose("<-----  {@message} received and handled! ", evt);
            }
            // Complete the message so that it is not received again.
            await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
        }

19 Source : CdmMessageProcessor.cs
with MIT License
from Azure

private async void CacheTimer_ElapsedAsync(object sender) {
            await _lock.WaitAsync();
            try {
                _cacheUploadTriggered = true;
                await PerformWriteCacheAsync();
            }
            finally {
                Try.Op(() => _cacheUploadTimer.Change(_cacheUploadInterval, Timeout.InfiniteTimeSpan));
                _cacheUploadTriggered = false;
                _lock.Release();
            }
        }

19 Source : CdmMessageProcessor.cs
with MIT License
from Azure

private async Task ProcessCdmSampleAsync<T>(T payload) {
            await _lock.WaitAsync();
            try {
                if (payload is MonitoredItemMessageModel sample) {

                    var key = GetNormalizedEnreplacedyName(sample);
                    if (!_samplesCache.TryGetValue(key, out var samplesList)) {
                        _samplesCache[key] = new List<MonitoredItemMessageModel>();
                    }
                    _samplesCache[key].Add(sample);
                }
                else if (payload is DataSetMessageModel dataSet) {
                    var key = GetNormalizedEnreplacedyName(dataSet);
                    if (!_dataSetsCache.TryGetValue(key, out var dataSetList)) {
                        _dataSetsCache[key] = new List<DataSetMessageModel>();
                    }
                    _dataSetsCache[key].Add(dataSet);
                }
                else {
                    throw new ArgumentException("Invalid payload type");
                }
                _samplesCacheSize++;
                if (!_cacheUploadTriggered && _samplesCacheSize >= kSamplesCacheMaxSize) {
                    Try.Op(() => _cacheUploadTimer.Change(TimeSpan.Zero, Timeout.InfiniteTimeSpan));
                    _cacheUploadTriggered = true;
                }
            }
            finally {
                _lock.Release();
            }
        }

19 Source : DiscoveryServices.cs
with MIT License
from Azure

public async Task DiscoverAsync(DiscoveryRequestModel request, CancellationToken ct) {
            kDiscoverAsync.Inc();
            if (request == null) {
                throw new ArgumentNullException(nameof(request));
            }
            var task = new DiscoveryRequest(request);
            var scheduled = _queue.TryAdd(task);
            if (!scheduled) {
                task.Dispose();
                _logger.Error("Discovey request not scheduled, internal server error!");
                var ex = new ResourceExhaustionException("Failed to schedule task");
                _progress.OnDiscoveryError(request, ex);
                throw ex;
            }
            await _lock.WaitAsync();
            try {
                if (_pending.Count != 0) {
                    _progress.OnDiscoveryPending(task.Request, _pending.Count);
                }
                _pending.Add(task);
            }
            finally {
                _lock.Release();
            }
        }

19 Source : DiscoveryServices.cs
with MIT License
from Azure

public async Task CancelAsync(DiscoveryCancelModel request, CancellationToken ct) {
            kCancelAsync.Inc();
            if (request == null) {
                throw new ArgumentNullException(nameof(request));
            }
            await _lock.WaitAsync();
            try {
                foreach (var task in _pending.Where(r => r.Request.Id == request.Id)) {
                    // Cancel the task
                    task.Cancel();
                }
            }
            finally {
                _lock.Release();
            }
        }

19 Source : DiscoveryServices.cs
with MIT License
from Azure

private async Task ProcessDiscoveryRequestAsync(DiscoveryRequest request) {
            _logger.Debug("Processing discovery request...");
            _progress.OnDiscoveryStarted(request.Request);
            object diagnostics = null;

            //
            // Discover servers
            //
            List<ApplicationRegistrationModel> discovered;
            try {
                discovered = await DiscoverServersAsync(request);
                request.Token.ThrowIfCancellationRequested();
                //
                // Upload results
                //
                await SendDiscoveryResultsAsync(request, discovered, DateTime.UtcNow,
                    diagnostics, request.Token);

                _progress.OnDiscoveryFinished(request.Request);
            }
            catch (OperationCanceledException) {
                _progress.OnDiscoveryCancelled(request.Request);
            }
            catch (Exception ex) {
                _progress.OnDiscoveryError(request.Request, ex);
            }
            finally {
                if (request != null) {
                    await _lock.WaitAsync();
                    try {
                        _pending.Remove(request);
                        Try.Op(() => request.Dispose());
                    }
                    finally {
                        _lock.Release();
                    }
                }
            }
        }

19 Source : DiscoveryServices.cs
with MIT License
from Azure

private async Task CancelPendingRequestsAsync() {
            _logger.Information("Cancelling all pending requests...");
            await _lock.WaitAsync();
            try {
                foreach (var request in _pending) {
                    _progress.OnDiscoveryCancelled(request.Request);
                    Try.Op(() => request.Dispose());
                }
                _pending.Clear();
            }
            finally {
                _lock.Release();
            }
            _logger.Information("Pending requests cancelled...");
        }

19 Source : DiscoveryServices.cs
with MIT License
from Azure

private async Task ReportPendingRequestsAsync() {
            // Notify all listeners about the request's place in queue
            await _lock.WaitAsync();
            try {
                for (var pos = 0; pos < _pending.Count; pos++) {
                    var item = _pending[pos];
                    if (!item.Token.IsCancellationRequested) {
                        _progress.OnDiscoveryPending(item.Request, pos);
                    }
                }
            }
            catch (Exception ex) {
                _logger.Warning(ex, "Failed to send pending event");
            }
            finally {
                _lock.Release();
            }
        }

19 Source : SupervisorServices.cs
with MIT License
from Azure

public async Task ActivateEndpointAsync(string id, string secret, CancellationToken ct) {
            await _lock.WaitAsync();
            try {
                if (_twinHosts.TryGetValue(id, out var twin) && twin.Running) {
                    _logger.Debug("{id} twin already running.", id);
                    return;
                }
                _logger.Debug("{id} twin starting...", id);
                _twinHosts.Remove(id);
                var host = new TwinHost(this, _config, id, secret, _logger);
                _twinHosts.Add(id, host);

                //
                // This starts and waits for the twin to be started - versus attaching which
                // represents the state of the actived and supervised twins in the supervisor
                // device twin.
                //
                await host.Started;
                _logger.Information("{id} twin started.", id);
            }
            finally {
                _lock.Release();
            }
        }

See More Examples