System.Collections.Concurrent.ConcurrentDictionary.GetOrAdd(string, System.Func, TArg)

Here are the examples of the csharp api System.Collections.Concurrent.ConcurrentDictionary.GetOrAdd(string, System.Func, TArg) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

637 Examples 7

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

private AsyncPolicy<IServiceResult> GetPolicy(string route, Type returnValueType)
        {
            return Policies.GetOrAdd(route, key =>
            {
                var service = ServiceFactory.Get(route);
                var serviceCircuitBreakerOptions = service.ServiceCircuitBreakerOptions;
                var circuitBreakerEvent = ServiceProvider.GetService<ICircuitBreakerEvent>();
                AsyncPolicy<IServiceResult> policy = Policy<IServiceResult>.Handle<Exception>().FallbackAsync<IServiceResult>(
                     async ct =>
                     {
                         //TODO 如果多次降级,根据路由排除此node
                         if (circuitBreakerEvent != null)
                             await circuitBreakerEvent.OnFallback(route, service.ClientMethodInfo);
                         if (returnValueType == null)
                             return new ServiceResult(null);
                         if (service.ServiceCircuitBreakerOptions.HasInjection)
                             return new ServiceResult(await ScriptInjection.Run(route));
                         return new ServiceResult(returnValueType.IsValueType ? Activator.CreateInstance(returnValueType) : default);
                     });
                if (serviceCircuitBreakerOptions.ExceptionsAllowedBeforeBreaking > 0)
                {
                    policy = policy.WrapAsync(Policy.Handle<Exception>().CircuitBreakerAsync(serviceCircuitBreakerOptions.ExceptionsAllowedBeforeBreaking, serviceCircuitBreakerOptions.DurationOfBreak,
                        async (ex, state, ts, ctx) =>
                        {
                            if (circuitBreakerEvent != null)
                                await circuitBreakerEvent.OnBreak(route, service.ClientMethodInfo, ex, ts);
                        },
                        async ctx =>
                        {
                            if (circuitBreakerEvent != null)
                                await circuitBreakerEvent.OnRest(route, service.ClientMethodInfo);
                        },
                        async () =>
                        {
                            if (circuitBreakerEvent != null)
                                await circuitBreakerEvent.OnHalfOpen(route, service.ClientMethodInfo);
                        }));
                }
                if (serviceCircuitBreakerOptions.Retry > 0)
                {
                    policy = policy.WrapAsync(Policy.Handle<Exception>().RetryAsync(serviceCircuitBreakerOptions.Retry,
                        async (ex, times) =>
                        {
                            if (circuitBreakerEvent != null)
                                await circuitBreakerEvent.OnRetry(route, service.ClientMethodInfo, ex, times);
                        }));
                }

                if (serviceCircuitBreakerOptions.MaxParallelization > 0)
                {
                    policy = policy.WrapAsync(Policy.BulkheadAsync(serviceCircuitBreakerOptions.MaxParallelization, serviceCircuitBreakerOptions.MaxQueuingActions, async ctx =>
                     {
                         if (circuitBreakerEvent != null)
                             await circuitBreakerEvent.OnBulkheadRejected(route, service.ClientMethodInfo);
                     }));
                }

                if (serviceCircuitBreakerOptions.Timeout.Ticks > 0)
                {
                    policy = policy.WrapAsync(Policy.TimeoutAsync(serviceCircuitBreakerOptions.Timeout, TimeoutStrategy.Pessimistic,
                        async (ctx, ts, task, ex) =>
                        {
                            if (circuitBreakerEvent != null)
                                await circuitBreakerEvent.OnTimeOut(route, service.ClientMethodInfo, ex);
                        }));
                }


                return policy;
            });
        }

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

public async Task<ServiceNodeInfo> GetNextNode(string serviceName, string serviceRoute, IReadOnlyList<object> serviceArgs,
            IReadOnlyDictionary<string, string> serviceMeta)
        {
            var nodes = await ServiceDiscovery.GetServiceNodes(serviceName);
            if (!nodes.Any())
                throw new NotFoundNodeException(serviceName);
            if (nodes.Count == 1)
                return nodes.First();
            lock (LockObject)
            {
                if (serviceMeta == null || !serviceMeta.TryGetValue("x-consistent-hash-key", out var key) || string.IsNullOrWhiteSpace(key))
                {
                    throw new ArgumentNullException(nameof(serviceMeta), "Service metadata [x-consistent-hash-key]  is null,Please call SetMeta method to preplaced in.");
                }

                var selectedNode= ServicesInfo.GetOrAdd(serviceName, k =>
                {
                    var consistentHash = new ConsistentHash<ServiceNodeInfo>();
                    foreach (var node in nodes)
                    {
                        consistentHash.AddNode(node, node.ServiceId);
                    }
                    ServicesInfo.TryAdd(serviceName, consistentHash);
                    return consistentHash;
                }).GetNodeForKey(key);
                if(Logger.IsEnabled( LogLevel.Trace))
                    Logger.LogTrace($"Load to node {selectedNode.ServiceId}.");
                return selectedNode;
            }
        }

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

void AddOrUpdateNavigateList(TEnreplacedy item) {
			Type itemType = null;
			foreach (var prop in _table.Properties) {
				if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue;
				if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue;

				object propVal = null;

				if (itemType == null) itemType = item.GetType();
				if (_table.TypeLazy != null && itemType == _table.TypeLazy) {
					var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, FieldInfo>()).GetOrAdd(prop.Key, propName =>
						_table.TypeLazy.GetField($"__lazy__{propName}", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance));
					if (lazyField != null) {
						var lazyFieldValue = (bool)lazyField.GetValue(item);
						if (lazyFieldValue == false) continue;
					}
					propVal = prop.Value.GetValue(item);
				} else {
					propVal = prop.Value.GetValue(item);
					if (propVal == null) continue;
				}

				var tref = _table.GetTableRef(prop.Key, true);
				if (tref == null) continue;

				switch(tref.RefType) {
					case Internal.Model.TableRefType.OneToOne:
					case Internal.Model.TableRefType.ManyToOne:
					case Internal.Model.TableRefType.ManyToMany:
						continue;
					case Internal.Model.TableRefType.OneToMany:
						var propValEach = propVal as IEnumerable;
						if (propValEach == null) continue;
						object dbset = null;
						MethodInfo dbsetAddOrUpdate = null;
						foreach (var propValItem in propValEach) {
							if (dbset == null) {
								dbset = _ctx.Set(tref.RefEnreplacedyType);
								dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdate", new Type[] { tref.RefEnreplacedyType });
							}
							for (var colidx = 0; colidx < tref.Columns.Count; colidx++) {
								tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName]
									.SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item));
							}
							dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem });
						}
						break;
				}
			}
		}

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

ILog IInternalLogManager.GetLog(string name)
            => _loggers.GetOrAdd(name, n => new Log(this, n));

19 View Source File : FileContainerServer.cs
License : MIT License
Project Creator : actions

private void UploadFileTraceReportReceived(object sender, ReportTraceEventArgs e)
        {
            ConcurrentQueue<string> logQueue = _fileUploadTraceLog.GetOrAdd(e.File, new ConcurrentQueue<string>());
            logQueue.Enqueue(e.Message);
        }

19 View Source File : FileContainerServer.cs
License : MIT License
Project Creator : actions

private void UploadFileProgressReportReceived(object sender, ReportProgressEventArgs e)
        {
            ConcurrentQueue<string> progressQueue = _fileUploadProgressLog.GetOrAdd(e.File, new ConcurrentQueue<string>());
            progressQueue.Enqueue($"Uploading '{e.File}' ({(e.CurrentChunk * 100) / e.TotalChunks}%)");
        }

19 View Source File : PerformanceProfiler.cs
License : MIT License
Project Creator : adainrivers

private PerformanceProfile GetOrAdd(string profileName)
        {
            return _profiles.GetOrAdd(profileName, p => new PerformanceProfile());
        }

19 View Source File : RestClient.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public RateLimitBucket GetBucket(RestRequestMethod method, string route, object route_params, out string url)
        {
            var rparams_props = route_params.GetType()
                .GetTypeInfo()
                .DeclaredProperties;
            var rparams = new Dictionary<string, string>();
            foreach (var xp in rparams_props)
            {
                var val = xp.GetValue(route_params);
                rparams[xp.Name] = val is string xs
                    ? xs
                    : val is DateTime dt
                    ? dt.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture)
                    : val is DateTimeOffset dto
                    ? dto.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture)
                    : val is IFormattable xf ? xf.ToString(null, CultureInfo.InvariantCulture) : val.ToString();
            }

            var guild_id = rparams.ContainsKey("guild_id") ? rparams["guild_id"] : "";
            var channel_id = rparams.ContainsKey("channel_id") ? rparams["channel_id"] : "";
            var webhook_id = rparams.ContainsKey("webhook_id") ? rparams["webhook_id"] : "";

            // Create a generic route (minus major params) key
            // ex: POST:/channels/channel_id/messages
            var hashKey = RateLimitBucket.GenerateHashKey(method, route);

            // We check if the hash is present, using our generic route (without major params)
            // ex: in POST:/channels/channel_id/messages, out 80c17d2f203122d936070c88c8d10f33
            // If it doesn't exist, we create an unlimited hash as our initial key in the form of the hash key + the unlimited constant
            // and replacedign this to the route to hash cache
            // ex: this.RoutesToHashes[POST:/channels/channel_id/messages] = POST:/channels/channel_id/messages:unlimited
            var hash = this.RoutesToHashes.GetOrAdd(hashKey, RateLimitBucket.GenerateUnlimitedHash(method, route));

            // Next we use the hash to generate the key to obtain the bucket.
            // ex: 80c17d2f203122d936070c88c8d10f33:guild_id:506128773926879242:webhook_id
            // or if unlimited: POST:/channels/channel_id/messages:unlimited:guild_id:506128773926879242:webhook_id
            var bucketId = RateLimitBucket.GenerateBucketId(hash, guild_id, channel_id, webhook_id);

            // If it's not in cache, create a new bucket and index it by its bucket id.
            var bucket = this.HashesToBuckets.GetOrAdd(bucketId, new RateLimitBucket(hash, guild_id, channel_id, webhook_id));

            bucket.LastAttemptAt = DateTimeOffset.UtcNow;

            // Cache the routes for each bucket so it can be used for GC later.
            if (!bucket.RouteHashes.Contains(bucketId))
                bucket.RouteHashes.Add(bucketId);

            // Add the current route to the request queue, which indexes the amount
            // of requests occurring to the bucket id.
            _ = this.RequestQueue.TryGetValue(bucketId, out var count);

            // Increment by one atomically due to concurrency
            this.RequestQueue[bucketId] = Interlocked.Increment(ref count);

            // Start bucket cleaner if not already running.
            if (!this._cleanerRunning)
            {
                this._cleanerRunning = true;
                this._bucketCleanerTokenSource = new CancellationTokenSource();
                this._cleanerTask = Task.Run(this.CleanupBucketsAsync, this._bucketCleanerTokenSource.Token);
                this.Logger.LogDebug(LoggerEvents.RestCleaner, "Bucket cleaner task started.");
            }

            url = RouteArgumentRegex.Replace(route, xm => rparams[xm.Groups[1].Value]);
            return bucket;
        }

19 View Source File : ChannelPool.cs
License : MIT License
Project Creator : albyho

public IChannelAccessor Acquire(string channelName = null, string connectionName = null)
        {
            CheckDisposed();

            channelName = channelName ?? DefaultChannelName;

            var poolItem = _channels.GetOrAdd(
                channelName,
                _ => new ChannelPoolItem(CreateChannel(connectionName))
            );

            poolItem.Acquire();

            return new ChannelAccessor(
                poolItem.Channel,
                channelName,
                () => poolItem.Release()
            );
        }

19 View Source File : SuperIndexer.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

public void SubmitGroupUpdate(IMessageContainer messageContainer, IEnumerable<Message> mostRecentMessages)
        {
            var messages = this.GroupUpdates.GetOrAdd(messageContainer.Id, new List<Message>());
            messages.AddRange(mostRecentMessages);
            Debug.WriteLine("Submitted updates for chat " + messageContainer.Name);
        }

19 View Source File : MultiTenantOptionsCache.cs
License : MIT License
Project Creator : alonsoalon

public void Clear()
        {
            var tenantId = _mulreplacedenantContextAccessor.MulreplacedenantContext?.TenantInfo?.Id ?? "";
            var cache = _map.GetOrAdd(tenantId, new OptionsCache<TOptions>());
            cache.Clear();
        }

19 View Source File : MultiTenantOptionsCache.cs
License : MIT License
Project Creator : alonsoalon

public void Clear(string tenantId)
        {
            tenantId = tenantId ?? "";
            var cache = _map.GetOrAdd(tenantId, new OptionsCache<TOptions>());

            cache.Clear();
        }

19 View Source File : MultiTenantOptionsCache.cs
License : MIT License
Project Creator : alonsoalon

public TOptions GetOrAdd(string name, Func<TOptions> createOptions)
        {
            if (createOptions == null)
            {
                throw new ArgumentNullException(nameof(createOptions));
            }

            name = name ?? Microsoft.Extensions.Options.Options.DefaultName;
            var tenantId = _mulreplacedenantContextAccessor.MulreplacedenantContext?.TenantInfo?.Id ?? "";
            var cache = _map.GetOrAdd(tenantId, new OptionsCache<TOptions>());

            return cache.GetOrAdd(name, createOptions);
        }

19 View Source File : MultiTenantOptionsCache.cs
License : MIT License
Project Creator : alonsoalon

public bool TryAdd(string name, TOptions options)
        {
            name = name ?? Microsoft.Extensions.Options.Options.DefaultName;
            var tenantId = _mulreplacedenantContextAccessor.MulreplacedenantContext?.TenantInfo?.Id ?? "";
            var cache = _map.GetOrAdd(tenantId, new OptionsCache<TOptions>());

            return cache.TryAdd(name, options);
        }

19 View Source File : MultiTenantOptionsCache.cs
License : MIT License
Project Creator : alonsoalon

public bool TryRemove(string name)
        {
            name = name ?? Microsoft.Extensions.Options.Options.DefaultName;
            var tenantId = _mulreplacedenantContextAccessor.MulreplacedenantContext?.TenantInfo?.Id ?? "";
            var cache = _map.GetOrAdd(tenantId, new OptionsCache<TOptions>());

            return cache.TryRemove(name);
        }

19 View Source File : ApnSender.cs
License : MIT License
Project Creator : andrei-m-code

private string GetJwtToken()
        {
            var (token, date) = tokens.GetOrAdd(settings.AppBundleIdentifier, _ => new Tuple<string, DateTime>(CreateJwtToken(), DateTime.UtcNow));
            if (date < DateTime.UtcNow.AddMinutes(-tokenExpiresMinutes))
            {
                tokens.TryRemove(settings.AppBundleIdentifier, out _);
                return GetJwtToken();
            }

            return token;
        }

19 View Source File : FileLoggerProvider.cs
License : MIT License
Project Creator : angelsix

public ILogger CreateLogger(string categoryName)
        {
            // Get or create the logger for this category
            return mLoggers.GetOrAdd(categoryName, name => new FileLogger(name, mFilePath, mConfiguration));
        }

19 View Source File : SetProvider.cs
License : MIT License
Project Creator : angshuman

public IStore GetOrAdd(string setId)
    {
        return _setList.GetOrAdd(setId, (key) => Store.Create(key, _graphProvider));
    }

19 View Source File : AzureFileStorage.cs
License : MIT License
Project Creator : ansel86castro

private async ValueTask<BlobContainerClient> GetContainerClient(string? container, bool createContainer, FileOptions? options = null)
        {
            if (container == null && _options.DefaultContainer == null)
                throw new InvalidOperationException("container name is missing");

            var containerClient = _blobClients.GetOrAdd(container ?? _options.DefaultContainer!, name =>
            {
                return _blobServiceClient.GetBlobContainerClient(name);
            });

            if (createContainer)
            {
                await containerClient.CreateIfNotExistsAsync(options?.Visibility != null ? GetPublicAccessType(options.Visibility.Value) : _options.DefaultAccessType);
            }

            return containerClient;
        }

19 View Source File : MemoryCacheMethod.cs
License : MIT License
Project Creator : Archomeda

public override Task SetAsync(CacheItem item)
        {
            if (item == null)
                throw new ArgumentNullException(nameof(item));

            if (item.ExpiryTime > DateTimeOffset.Now)
            {
                var cache = this.cachedItems.GetOrAdd(item.Category, new ConcurrentDictionary<string, CacheItem>());
                cache[item.Id] = item;
            }
            return Task.CompletedTask;
        }

19 View Source File : CachingPermissionRepository.cs
License : MIT License
Project Creator : ASF-Framework

public Task<IList<Permission>> GetList()
        {
            IList<Permission> list = cache.Values.ToList();
            if (list.Count > 0)
                return Task.FromResult(list);
            else
            {
                return this.Do(repository =>
                {
                    var _list = repository.GetList().GetAwaiter().GetResult();
                    foreach (var data in _list)
                    {
                        cache.GetOrAdd(data.Id, data);
                    }
                    return Task.FromResult(_list);
                });
            }
        }

19 View Source File : CachingPermissionRepository.cs
License : MIT License
Project Creator : ASF-Framework

public Task<Permission> AddAsync(Permission enreplacedy)
        {
            enreplacedy = cache.GetOrAdd(enreplacedy.Id, key =>
            {
                return this.Do(repository =>
                {
                    return repository.AddAsync(enreplacedy).GetAwaiter().GetResult();
                });
            });
            return Task.FromResult(enreplacedy);
        }

19 View Source File : MemoryWebHookStore.cs
License : Apache License 2.0
Project Creator : aspnet

public override Task<StoreResult> InsertWebHookAsync(string user, WebHook webHook)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (webHook == null)
            {
                throw new ArgumentNullException(nameof(webHook));
            }

            user = NormalizeKey(user);

            ConcurrentDictionary<string, WebHook> userHooks = _store.GetOrAdd(user, key => new ConcurrentDictionary<string, WebHook>());

            string id = NormalizeKey(webHook.Id);
            bool inserted = userHooks.TryAdd(id, webHook);
            StoreResult result = inserted ? StoreResult.Success : StoreResult.Conflict;
            return Task.FromResult(result);
        }

19 View Source File : StorageManager.cs
License : Apache License 2.0
Project Creator : aspnet

public CloudTable GetCloudTable(string connectionString, string tableName)
        {
            if (connectionString == null)
            {
                throw new ArgumentNullException(nameof(connectionString));
            }
            if (tableName == null)
            {
                throw new ArgumentNullException(nameof(tableName));
            }

            var tableKey = GetLookupKey(connectionString, tableName);
            var account = TableAccounts.GetOrAdd(
                tableKey,
                key =>
                {
                    var storageAccount = GetCloudStorageAccount(connectionString);
                    try
                    {
                        // Ensure that table exists
                        var client = storageAccount.CreateCloudTableClient();
                        var cloudTable = client.GetTableReference(tableName);
                        cloudTable.CreateIfNotExists();
                    }
                    catch (Exception ex)
                    {
                        var error = GetStorageErrorMessage(ex);
                        var message = string.Format(CultureInfo.CurrentCulture, AzureStorageResources.StorageManager_InitializationFailure, error);
                        _logger.Error(message, ex);
                        throw new InvalidOperationException(message, ex);
                    }

                    return storageAccount;
                });

            var cloudClient = account.CreateCloudTableClient();
            return cloudClient.GetTableReference(tableName);
        }

19 View Source File : StorageManager.cs
License : Apache License 2.0
Project Creator : aspnet

public CloudQueue GetCloudQueue(string connectionString, string queueName)
        {
            if (connectionString == null)
            {
                throw new ArgumentNullException(nameof(connectionString));
            }
            if (queueName == null)
            {
                throw new ArgumentNullException(nameof(queueName));
            }

            var queueKey = GetLookupKey(connectionString, queueName);
            var account = QueueAccounts.GetOrAdd(
                queueKey,
                key =>
                {
                    var storageAccount = GetCloudStorageAccount(connectionString);
                    try
                    {
                        // Ensure that queue exists
                        var client = storageAccount.CreateCloudQueueClient();
                        var cloudQueue = client.GetQueueReference(queueName);
                        cloudQueue.CreateIfNotExists();
                    }
                    catch (Exception ex)
                    {
                        var error = GetStorageErrorMessage(ex);
                        var message = string.Format(CultureInfo.CurrentCulture, AzureStorageResources.StorageManager_InitializationFailure, error);
                        _logger.Error(message, ex);
                        throw new InvalidOperationException(message, ex);
                    }

                    return storageAccount;
                });

            var cloudClient = account.CreateCloudQueueClient();
            return cloudClient.GetQueueReference(queueName);
        }

19 View Source File : FeatureResultData.cs
License : MIT License
Project Creator : autostep

public ScenarioInvocationResultData AddScenarioInvocation(IScenarioInfo scenario, DateTime startTimeUtc, string? invocationName, TableVariableSet? outlineVariables)
        {
            if (scenario is null)
            {
                throw new ArgumentNullException(nameof(scenario));
            }

            var scenarioData = scenarioLookup.GetOrAdd(scenario.Name, k =>
            {
                var newData = new ScenarioResultData(scenario);

                // Scenarios could be added from multiple threads.
                lock (orderedSet)
                {
                    orderedSet.Add(newData);
                }

                return newData;
            });

            return scenarioData.AddInvocation(startTimeUtc, invocationName, outlineVariables);
        }

19 View Source File : TestLogProvider.cs
License : MIT License
Project Creator : autostep

public ILogger CreateLogger(string categoryName)
        {
            return loggers.GetOrAdd(categoryName, (n) => new TestLogger(this, n));
        }

19 View Source File : ExpectEventPublisher.cs
License : MIT License
Project Creator : Avanade

public override IEventPublisher Publish(params EventData[] events)
        {
            if (ExecutionContext.HasCurrent && ExecutionContext.Current.CorrelationId != null)
            {
                var list = _publishedEventDict.GetOrAdd(ExecutionContext.Current.CorrelationId, new List<EventData>());
                list.AddRange(events);
            }

            return base.Publish(events);
        }

19 View Source File : ExpectEventPublisher.cs
License : MIT License
Project Creator : Avanade

public override EventData[] GetEvents()
        {
            var events = base.GetEvents();

            if (ExecutionContext.HasCurrent && ExecutionContext.Current.CorrelationId != null)
            {
                var list = _sentEventDict.GetOrAdd(ExecutionContext.Current.CorrelationId, new List<EventData>());
                list.AddRange(events);

                _sentCountDict.AddOrUpdate(ExecutionContext.Current.CorrelationId, 1, (_, count) => count++);
            }

            return events;
        }

19 View Source File : CorrelationIdLogger.cs
License : MIT License
Project Creator : Avanade

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
                return;

            if (formatter == null)
                throw new ArgumentNullException(nameof(formatter));

            var message = formatter(state, exception);

            if (string.IsNullOrEmpty(message))
                return;

            var id = ExecutionContext.HasCurrent && ExecutionContext.Current.CorrelationId != null ? ExecutionContext.Current.CorrelationId : DefaultId;

            var timestamp = DateTime.Now;
            message = $"{timestamp.ToString("yyyy-MM-ddTHH:mm:ss.ffff", DateTimeFormatInfo.InvariantInfo)} {GetLogLevel(logLevel)}: {message} [{_name}]{(id == DefaultId ? "*" : "")}";

            if (exception != null)
                message += Environment.NewLine + exception;

            var msgs = _messageDict.GetOrAdd(id, new List<(DateTime, string)>());
            msgs.Add((timestamp, message));
        }

19 View Source File : SingleLineJsonParser.cs
License : Apache License 2.0
Project Creator : awslabs

public IEnumerable<IEnvelope<JObject>> ParseRecords(StreamReader sr, LogContext context)
        {
            var baseStream = sr.BaseStream;
            var filePath = context.FilePath;
            var lineReader = _readers.GetOrAdd(filePath, f => new FileLineReader());
            if (context.Position > baseStream.Position)
            {
                baseStream.Position = context.Position;
            }
            else if (context.Position == 0)
            {
                // this might happen due to the file being truncated
                // in that case, we need to reset the reader's state
                lineReader.Reset();
                context.LineNumber = 0;
            }

            string line;
            do
            {
                line = lineReader.ReadLine(baseStream, sr.CurrentEncoding ?? Encoding.UTF8);
                if (line is null)
                {
                    yield break;
                }

                context.LineNumber++;
                _logger.LogDebug("ReadLine '{0}'", line);

                if (line.Length == 0)
                {
                    // an 'empty' line, ignore
                    continue;
                }

                JObject jObject;
                try
                {
                    jObject = JObject.Parse(line);
                }
                catch (JsonReaderException jre)
                {
                    _logger.LogError(0, jre, "Error parsing log file '{0}' at line {1}", filePath, context.LineNumber);
                    jObject = null;
                }

                if (jObject is null)
                {
                    // this means that the line is not a valid JSON, skip and read next line
                    continue;
                }

                yield return new LogEnvelope<JObject>(jObject,
                       _getTimestamp(jObject),
                       line,
                       context.FilePath,
                       context.Position,
                       context.LineNumber);
            } while (line != null);
        }

19 View Source File : InstrumentationDaemon.cs
License : MIT License
Project Creator : azist

public void Record(Datum datum)
    {
      if (Status != DaemonStatus.Active) return;
      if (datum == null) return;

      datum.InitDefaultFields(App);

      if (Overflown) return;

      var t = datum.GetType();

      var srcBucketed = m_TypeBucketed.GetOrAdd(t, (tp) => new SrcBucketedData());

      if (srcBucketed.DefaultDatum == null)
        srcBucketed.DefaultDatum = datum;

      var bag = srcBucketed.GetOrAdd(datum.Source, (src) => new DatumBag());

      bag.Add(datum);
      Interlocked.Increment(ref m_RecordCount);
    }

19 View Source File : NetGate.cs
License : MIT License
Project Creator : azist

private void setVariable(bool inc, TrafficDirection direction, string address, string varName, int value)
      {
        if (!Running || address.IsNullOrWhiteSpace() || varName.IsNullOrWhiteSpace() || value==0) return;

        var state = this[direction];
        var grp = state.FindGroupForAddress(address);

        var key = grp==null ? address : grp.Key;

        var nstate = state.NetState.GetOrAdd(key, (k) => grp==null ? new NetSiteState(address) : new NetSiteState(grp));

        lock(nstate)
        {
          if (inc)
          {
           NetSiteState._value vval;
           if (!nstate.m_Variables.TryGetValue(varName, out vval))
           {
             nstate.m_Variables[varName] = vval = new NetSiteState._value();
           }
           vval.Value += value;
          }
          else
           nstate.m_Variables[varName] = new NetSiteState._value{Value = value};
        }
      }

19 View Source File : DataCache.cs
License : MIT License
Project Creator : Azure

public Task<dynamic> GetOrAdd(string key, Func<string, CacheMember> cacheMember)
        {
            return _cache.GetOrAdd(key, cacheMember).DataTask;
        }

19 View Source File : RuntimeLogger.cs
License : MIT License
Project Creator : Azure

public ILogger CreateLogger(string categoryName)
        {
            if (string.IsNullOrWhiteSpace(categoryName))
            {
                return null;
            }
            return _loggers.GetOrAdd(categoryName, (category) => new RuntimeLogger(this, category));
        }

19 View Source File : TestLoggerProvider.cs
License : MIT License
Project Creator : Azure

public ILogger CreateLogger(string categoryName)
        {
            return LoggerCache.GetOrAdd(categoryName, (key) => new TestLogger(key, _scopeProvider));
        }

19 View Source File : DefaultInputConversionFeature.cs
License : MIT License
Project Creator : Azure

private static string? GetConverterTypeNameFromAttributeOnType(Type targetType)
        {
            return _typeToConverterCache.GetOrAdd(targetType.replacedemblyQualifiedName!, (key, type) =>
            {
                var converterAttribute = type.GetCustomAttributes(_inputConverterAttributeType, inherit: true)
                                             .FirstOrDefault();

                if (converterAttribute is null)
                {
                    return null;
                }

                Type converterType = ((InputConverterAttribute)converterAttribute).ConverterType;
                return converterType.replacedemblyQualifiedName!;

            }, targetType);
        }

19 View Source File : DefaultInputConverterProvider.cs
License : MIT License
Project Creator : Azure

public IInputConverter GetOrCreateConverterInstance(string converterTypeName)
        {
            if (converterTypeName is null)
            {
                throw new ArgumentNullException((nameof(converterTypeName)));
            }

            // Get from cache or create the instance and cache
            return _converterCache.GetOrAdd(converterTypeName, (key, converterTypereplacedemblyQualifiedName) =>
            {
                // Create the instance and cache that against the replacedembly qualified name of the type.
                var converterType = Type.GetType(converterTypereplacedemblyQualifiedName);

                if (converterType is null)
                {
                    throw new InvalidOperationException($"Could not create an instance of {converterTypereplacedemblyQualifiedName}.");
                }

                EnsureTypeCanBereplacedigned(converterType);

                return (IInputConverter)ActivatorUtilities.CreateInstance(_serviceProvider, converterType);

            }, converterTypeName);
        }

19 View Source File : DefaultFunctionExecutor.cs
License : MIT License
Project Creator : Azure

public async Task ExecuteAsync(FunctionContext context)
        {
            var invoker = _invokerCache.GetOrAdd(context.FunctionId,
                _ => _invokerFactory.Create(context.FunctionDefinition));

            object? instance = invoker.CreateInstance(context);
            var modelBindingFeature = context.Features.Get<IModelBindingFeature>();

            object?[] inputArguments;
            if (modelBindingFeature is null)
            {
                Log.ModelBindingFeatureUnavailable(_logger, context);
                inputArguments = new object?[context.FunctionDefinition.Parameters.Length];
            }
            else
            {
                inputArguments = await modelBindingFeature.BindFunctionInputAsync(context);
            }

            context.GetBindings().InvocationResult = await invoker.InvokeAsync(instance, inputArguments);
        }

19 View Source File : KafkaProducerFactory.cs
License : MIT License
Project Creator : Azure

public IKafkaProducer Create(KafkaProducerEnreplacedy enreplacedy)
        {
            AzureFunctionsFileHelper.InitializeLibrdKafka(this.loggerProvider.CreateLogger(LogCategories.CreateTriggerCategory("Kafka")));

            // Goal is to create as less producers as possible
            // We can group producers based on following criterias
            // - Broker List
            // - Configuration
            var producerConfig = this.GetProducerConfig(enreplacedy);
            var producerKey = CreateKeyForConfig(producerConfig);

            var baseProducer = baseProducers.GetOrAdd(producerKey, (k) => CreateBaseProducer(producerConfig));
            return Create(baseProducer.Handle, enreplacedy);
        }

19 View Source File : KafkaLanguageEndToEndFixture.cs
License : MIT License
Project Creator : Azure

public IConsumer<string, string> ConsumerFactory(string key)
        {
            return consumers.GetOrAdd(key, (key) =>
             {
                 var config = new ConsumerConfig
                 {
                     BootstrapServers = this.Broker,
                     GroupId = key,
                     EnableAutoCommit = true
                 };

                 return new ConsumerBuilder<string, string>(config).SetLogHandler((k, v) => Console.WriteLine($"KafkaConsumer: {key} :{v?.Message}")).Build();
             });
        }

19 View Source File : ServiceManagerStore.cs
License : MIT License
Project Creator : Azure

public IInternalServiceHubContextStore GetOrAddByConnectionStringKey(string connectionStringKey)
        {
            if (string.IsNullOrWhiteSpace(connectionStringKey))
            {
                throw new ArgumentException($"'{nameof(connectionStringKey)}' cannot be null or whitespace", nameof(connectionStringKey));
            }
            return store.GetOrAdd(connectionStringKey, CreateHubContextStore);
        }

19 View Source File : ServiceHubContextStore.cs
License : MIT License
Project Creator : Azure

public ValueTask<IServiceHubContext> GetAsync(string hubName)
        {
            var pair = store.GetOrAdd(hubName,
                (new Lazy<Task<IServiceHubContext>>(
                    () => ServiceManager.CreateHubContextAsync(hubName)), default));
            return GetAsyncCore(hubName, pair);
        }

19 View Source File : RabbitMQExtensionConfigProvider.cs
License : MIT License
Project Creator : Azure

internal IRabbitMQService GetService(string connectionString, string hostName, string queueName, string userName, string preplacedword, int port)
        {
            string[] keyArray = { connectionString, hostName, queueName, userName, preplacedword, port.ToString() };
            string key = string.Join(",", keyArray);
            return _connectionParametersToService.GetOrAdd(key, _ => _rabbitMQServiceFactory.CreateService(connectionString, hostName, queueName, userName, preplacedword, port));
        }

19 View Source File : RabbitMQExtensionConfigProvider.cs
License : MIT License
Project Creator : Azure

internal IRabbitMQService GetService(string connectionString, string hostName, string userName, string preplacedword, int port)
        {
            string[] keyArray = { connectionString, hostName, userName, preplacedword, port.ToString() };
            string key = string.Join(",", keyArray);
            return _connectionParametersToService.GetOrAdd(key, _ => _rabbitMQServiceFactory.CreateService(connectionString, hostName, userName, preplacedword, port));
        }

19 View Source File : ServiceEndpointManagerBase.cs
License : MIT License
Project Creator : Azure

public IReadOnlyList<HubServiceEndpoint> GetEndpoints(string hub)
        {
            return _endpointsPerHub.GetOrAdd(hub, s => Endpoints.Select(e => CreateHubServiceEndpoint(hub, e.Key)).ToArray());
        }

19 View Source File : DynamicHubContextStore.cs
License : MIT License
Project Creator : Azure

public DynamicHubContext GetOrAdd(string hub)
        {
            return _hubContextCache.GetOrAdd(hub, s => new Lazy<DynamicHubContext>(() => CreateHubContextImpl(hub), true)).Value;
        }

19 View Source File : GroupManager.cs
License : MIT License
Project Creator : Azure

public void AddUserToGroup(string user, string group, DateTimeOffset expireAt)
        {
            _userGroupMap.Add(user, group);
            lock (_expires)
            {
                _expires[(user, group)] = expireAt;
            }
            _ = CleanExpiresAsync();
            var conns = _userConnections.GetOrAdd(user, _ => new Connections());
            lock (conns)
            {
                foreach (var conn in conns)
                {
                    _connectionGroupMap.Add(conn.ConnectionId, group);
                }
            }
        }

19 View Source File : TestClientConnectionManager.cs
License : MIT License
Project Creator : Azure

public Task<IServiceTransport> CreateConnection(OpenConnectionMessage message)
        {
            var transport = new TestTransport
            {
                ConnectionId = message.ConnectionId
            };
            CurrentTransports.TryAdd(message.ConnectionId, transport);

            var tcs = _waitForConnectionOpen.GetOrAdd(message.ConnectionId, i => new TaskCompletionSource<ConnectionContext>(TaskCreationOptions.RunContinuationsAsynchronously));

            tcs.TrySetResult(null);

            return Task.FromResult<IServiceTransport>(transport);
        }

19 View Source File : TestClientConnectionManager.cs
License : MIT License
Project Creator : Azure

public Task WaitForClientConnectAsync(string connectionId)
        {
            var tcs = _waitForConnectionOpen.GetOrAdd(connectionId, i => new TaskCompletionSource<ConnectionContext>(TaskCreationOptions.RunContinuationsAsynchronously));

            return tcs.Task;
        }

See More Examples