public bool Add(T item) { if (!_rules.ContainsKey(item.Tag)) { _rules.GetOrAdd(item.Tag, item); return(true); } return(false); }
/// <inheritdoc /> public void Handle(IMessageContext messageContext) { // Find handler method, first try to find cached value. var cmdtype = messageContext.Content.GetType(); var method = cache.GetOrAdd(cmdtype, FindOrCreateMethodHandler); if (InternalLogger.IsDebugEnabled) { InternalLogger.Debug(string.Format(Properties.Strings.SearchCommandHandler, cmdtype.Name), nameof(CommandHandlerLocatorMiddleware)); } if (method == null) { method = cmdtype.GetTypeInfo().GetMethod(HandlerPrefix); if (method == null) { var assembliesStr = string.Join(",", Assemblies.Select(a => a.FullName)); InternalLogger.Warn(string.Format(Properties.Strings.SearchCommandHandlerNotFound, cmdtype.Name, assembliesStr), nameof(CommandHandlerLocatorMiddleware)); throw new CommandHandlerNotFoundException(cmdtype.Name); } } if (InternalLogger.IsDebugEnabled) { InternalLogger.Debug(string.Format(Properties.Strings.CommandHandlerFound, method, cmdtype), nameof(CommandHandlerLocatorMiddleware)); } messageContext.Items[HandlerMethodKey] = method; }
/// <summary> /// Генерирует новый или возвращает ранее сконструированный тип на базе типа <typeparamref name="TMapper"/>, наследующий и реализующий методы интерфейса <typeparamref name="TInterface"/>. /// Обращение к свойствам и методам объекта через интерфейса на основе сконструированного типа должно обрабатываться в <see cref="MapperBase.OnPrepareMethodCall(MethodInfo, object[])"/> / <see cref="MapperBase.OnPreparePropertyGet(PropertyInfo)"/> / <see cref="MapperBase.OnPreparePropertySet(PropertyInfo, object)"/>. /// <para>После создания сконструированный тип сопоставляется паре <typeparamref name="TMapper"/>-<typeparamref name="TInterface"/> и повторно возвращается при последующих вызовах данной пары.</para> /// </summary> public static Type CreateTypeFromInterface <TMapper, TInterface>() where TMapper : MapperBase { var type = typeof(TInterface); var instanceType = _proxyTypes.GetOrAdd(type, (key) => CreateTypeFromParentInternal <TMapper, TInterface>()); return(instanceType); }
public static IDbValueReader GetDbValueReader(Type type) { var handler = GetValueHandlerCache.GetOrAdd(type, valueType => { valueType = valueType.GetUnderlyingType(); if (valueType.IsEnum) { return(new DbValueReader((IDataReader reader, int ordinal) => { object value = reader.GetEnum(ordinal, valueType); return value; })); } Infrastructure.MappingType mappingType = MappingTypeSystem.GetMappingType(valueType); return(new DbValueReader((IDataReader reader, int ordinal) => { object value = DataReaderExtension.GetValue(reader, ordinal); if (value == null) { return null; } if (value.GetType() == mappingType.Type) { return value; } return mappingType.DbValueConverter.Convert(value); })); }); return(handler); }
private static object GetOrAdd(string key) { CountedLock padlock = m_waitLock.GetOrAdd(key, LockFactory); padlock.Increment(); return(padlock); }
private void IncreaseHelper(Site site, string pageVisitRule, string matchedPage, Action <ABPageTestResult, ABPageTestHits> increaseFunc) { ABPageTestResult abPageTestResult = null; abPageTestResult = results.GetOrAdd(pageVisitRule, (key) => { abPageTestResult = Get(site, key); if (abPageTestResult == null) { abPageTestResult = new ABPageTestResult() { Site = site, ABPageUUID = key, PageHits = new List <ABPageTestHits>() }; this.Add(site, abPageTestResult); } return(abPageTestResult); }); if (abPageTestResult != null) { lock (abPageTestResult) { var pageHit = abPageTestResult.PageHits.Where(it => it.PageName.EqualsOrNullEmpty(matchedPage, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); increaseFunc(abPageTestResult, pageHit); this.Update(site, abPageTestResult, abPageTestResult); } } }
private static Action <TSrc, Targ> GetMapper <TSrc, Targ>() { Type target = typeof(Targ); Type src = typeof(TSrc); var name = string.Format("{0}To{1}", Utility.GetValidString(src.FullName), Utility.GetValidString(target.FullName)); return((Action <TSrc, Targ>)delegates.GetOrAdd(name, (n) => { var srcProps = src.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); var trgtProps = target.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); var sr = Expression.Parameter(src); var trgt = Expression.Parameter(target); ClassConstructor cc = new ClassConstructor(name); MethodConstructor mc = new MethodConstructor("Copy", Expression.Lambda <Action <TSrc, Targ> >( Expression.Block( (from item in trgtProps from s in srcProps where item.Name == s.Name && item.PropertyType == s.PropertyType select Expression.Assign(Expression.Property(trgt, item.Name), Expression.Property(sr, item.Name)))), sr, trgt), System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.Static); cc.AddMethod(mc); _manager.AddType(cc); _manager.BuildClass(AppDomain.CurrentDomain, cc.Name); return mc.CreateDelegate(typeof(Action <TSrc, Targ>)); })); }
static System.Collections.Generic.List <BindItem> TryGetBind(System.Type entityType) { string key = entityType.AssemblyQualifiedName; var list = _list_key.GetOrAdd(key, (p) => { if (entityType.IsValueType || entityType == typeof(string) || entityType == typeof(object) || TypeExtensions.IsNullableType(entityType)) { return(null); } var cache = new System.Collections.Generic.List <BindItem>(); foreach (System.Reflection.PropertyInfo propertyInfo in entityType.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.SetProperty)) { var binder = AttributeExtensions.GetCustomAttribute <DataBinderAttribute>(propertyInfo); if (binder == null) { continue; } BindItem bindItem = new BindItem() { propertyInfo = propertyInfo, binder = binder, bindAction = binder.Bind, }; cache.Add(bindItem); } return(cache); }); return(list); }
private static CultureLanguages loadCultureLanguages(System.Globalization.CultureInfo culture) { return(keyValues.GetOrAdd(culture.Name, ff => { return loadCultureLanguage(culture.Name); })); }
/// <summary> /// Refresh all lazy initializations. /// </summary> private void Refresh() { lock (this.syncRoot) { if (this.registeredColumnBindings == null || this.registeredColumnBindings.IsValueCreated) { this.registeredColumnBindings = new Lazy <ConcurrentTypeDictionary <IColumnBinding> >( () => { var bindings = new ConcurrentTypeDictionary <IColumnBinding>(); foreach (var kv in this.columnBindings) { bindings.TryAdd(kv.Key, kv.Value.Binding); } return(bindings); }); } if (this.registeredColumnNames == null || this.registeredColumnNames.IsValueCreated) { this.registeredColumnNames = new Lazy <IDictionary <string, ISet <string> > >( () => { var columnNames = new System.Collections.Concurrent.ConcurrentDictionary <string, ISet <string> >(); foreach (var binding in this.RegisteredColumnBindings().Values) { var columnQualifiers = columnNames.GetOrAdd(binding.ColumnFamily, _ => new ConcurrentSet <string>()); if (binding.ColumnQualifier != null) { columnQualifiers.Add(binding.ColumnQualifier); } } return(columnNames); }); } if (this.registeredTableBindings == null || this.registeredTableBindings.IsValueCreated) { this.registeredTableBindings = new Lazy <ConcurrentTypeDictionary <ITableBinding> >( () => { var bindings = new ConcurrentTypeDictionary <ITableBinding>(); foreach (var kv in this.tableBindings) { bindings.TryAdd(kv.Key, kv.Value.Binding); } return(bindings); }); } } this.preliminaryEntityReferences.Clear(); }
static int _m_GetOrAdd(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Collections.Concurrent.ConcurrentDictionary <long, ulong> gen_to_be_invoked = (System.Collections.Concurrent.ConcurrentDictionary <long, ulong>)translator.FastGetCSObj(L, 1); int gen_param_count = LuaAPI.lua_gettop(L); if (gen_param_count == 3 && (LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 2) || LuaAPI.lua_isint64(L, 2)) && (LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 3) || LuaAPI.lua_isuint64(L, 3))) { long _key = LuaAPI.lua_toint64(L, 2); ulong _value = LuaAPI.lua_touint64(L, 3); ulong gen_ret = gen_to_be_invoked.GetOrAdd( _key, _value); LuaAPI.lua_pushuint64(L, gen_ret); return(1); } if (gen_param_count == 3 && (LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 2) || LuaAPI.lua_isint64(L, 2)) && translator.Assignable <System.Func <long, ulong> >(L, 3)) { long _key = LuaAPI.lua_toint64(L, 2); System.Func <long, ulong> _valueFactory = translator.GetDelegate <System.Func <long, ulong> >(L, 3); ulong gen_ret = gen_to_be_invoked.GetOrAdd( _key, _valueFactory); LuaAPI.lua_pushuint64(L, gen_ret); return(1); } } catch (System.Exception gen_e) { return(LuaAPI.luaL_error(L, "c# exception:" + gen_e)); } return(LuaAPI.luaL_error(L, "invalid arguments to System.Collections.Concurrent.ConcurrentDictionary<long, ulong>.GetOrAdd!")); }
public static MemberValueGetter GetMemberValueGetter(MemberInfo memberInfo) { MemberValueGetter getter = Cache.GetOrAdd(memberInfo, member => { return(DelegateGenerator.CreateValueGetter(member)); }); return(getter); }
/// <summary> /// Validates this instance. /// </summary> protected override void Validate() { foreach (var validator in _validators) { //var method = _validatorMethods.GetOrAdd(validator.GetType(), validator.GetType().GetMethod(nameof(IConfigurationObjectValidator<TInterface>.Validate)).MakeGenericMethod(new[] { typeof(TInterface) })); var method = _validatorMethods.GetOrAdd(validator.GetType(), validator.GetType().GetMethod(nameof(IConfigurationObjectValidator <TInterface> .Validate))); method.Invoke(validator, new object[] { this }); } }
public static System.IO.Stream GetManifestResourceStreamIgnoreCase(this System.Reflection.Assembly assembly, string name) { var key = assembly.FullName + name; var r = keyValuePairs.GetOrAdd(key, keyName => { return(assembly.GetManifestResourceNames().FirstOrDefault(f => f.Equals(name, StringComparison.InvariantCultureIgnoreCase))); }); return(assembly.GetManifestResourceStream(r)); }
//遅いしメモリの大量消費 private int Count14ConcurrentDictionaryBoolean_32bpp(byte[] pixels) { var cd = new System.Collections.Concurrent.ConcurrentDictionary <uint, bool>(); Parallel.For(0, pixels.Length / 4, i => { cd.GetOrAdd((uint)(pixels[i * 4] | (pixels[i * 4 + 1] << 8) | (pixels[i * 4 + 2] << 16) | (pixels[i * 4 + 3] << 24)), true); }); return(cd.Distinct().ToArray().Length); }
ActiveRangeCollection GetActiveRangeCollection(int threadId) { ActiveRangeCollection collection; if (!_activeRanges.TryGetValue(threadId, out collection)) { collection = _activeRanges.GetOrAdd(threadId, new ActiveRangeCollection()); } return(collection); }
ActiveRangeCollection GetActiveRangeCollection(int threadId) { ActiveRangeCollection collection = _activeRanges.GetOrAdd(threadId, tid => { var parentCollection = (Parent != null) ? Parent.GetActiveRangeCollection(tid) : null; var newCollection = new ActiveRangeCollection(parentCollection); return(newCollection); }); return(collection); }
protected bool GetCertficate() { // if not in Cache? var cacheItem = Cache.GetOrAdd(Header.CertChainUrl, // Add (key) => new LocalCertCache() { ValidUntil = DateTime.UtcNow.AddHours(24) }); if (cacheItem.ValidUntil < DateTime.UtcNow) { cacheItem.CertBytes = null; } if (cacheItem.CertBytes == null) { { var certdata = RetrieveCertificate(); if (certdata == null) { return(false); } cacheItem.CertBytes = certdata; cacheItem.ValidUntil = DateTime.UtcNow.AddHours(24); } } if (!CreateCertificate(cacheItem.CertBytes)) { return(false); } if (!VerifyCertificate()) { return(false); } return(true); }
public void Add(string key, JSFunctionMetadata func) { //TODO: can we make this call async? Debug.Assert(func != null, "Cannot add null function for {0}", key); LinkedList <JSFunctionMetadata> funcs = null; if (!_map.TryGetValue(key, out funcs)) { funcs = _map.GetOrAdd(key, k => new LinkedList <JSFunctionMetadata>()); } funcs.AddLast(func); }
/// <summary> /// Memoizes the specified function. /// </summary> public static Func <TArg, TRes> Memoize <TArg, TRes> ( [NotNull] this Func <TArg, TRes> func ) { #if WINMOBILE || POCKETPC || SILVERLIGHT throw new NotImplementedException(); #else var dictionary = new System.Collections.Concurrent.ConcurrentDictionary <TArg, TRes>(); return(arg => dictionary.GetOrAdd(arg, func)); #endif }
static QueryResult InvokeQueryResultConstructor(Type type, object value) { Func <object, QueryResult> func = _newQueryResultMap.GetOrAdd(type, key => { Type queryResultType = typeof(QueryResult <>).MakeGenericType(key); ConstructorInfo constructor = queryResultType.GetConstructor(new Type[] { key }); ParameterExpression parameter = Expression.Parameter(typeof(object)); NewExpression constructorExpression = Expression.New(constructor, Expression.Convert(parameter, key)); return(Expression.Lambda <Func <object, QueryResult> >(constructorExpression, parameter).Compile()); }); return(func.Invoke(value)); }
/// <summary> /// Prevents parallel execution of the FuncAsync for a SAME PARAMETER /// </summary> /// <param name="func">Func to lock</param> /// <param name="mode">Mode to use for locking FOR A SAME PARAMETER</param> /// <returns>A FuncAsync which cannot have nmultiple instance running at a same time</returns> public static FuncAsync <TParam, TResult> LockInvocation <TParam, TResult>(this FuncAsync <TParam, TResult> func, InvocationLockingMode mode = InvocationLockingMode.Share) where TParam : class { // Note: Do not use TaskCompletionSource, for strange reasons it cause app crashes on iOS (on SetException). // Prefer keep task by themselves instead of trying to replicate task state to a TaskCompletionSource. if (mode == InvocationLockingMode.Share) { #if HAS_NO_CONCURRENT_DICT var pendings = new SynchronizedDictionary <TParam, Task <TResult> >(); #else var pendings = new System.Collections.Concurrent.ConcurrentDictionary <TParam, Task <TResult> >(); #endif return(async(ct, param) => { var created = false; try { return await pendings.GetOrAdd(param, p => { created = true; return func(ct, p); }); } finally { // Note: Keep trace of the creation and let to the initiator the responsibility to removed the task from pendings // DO NOT auto remove at the end of the task itself: If the task run synchronously, we might TryRemove the task before it is actually added to the pendings. if (created) { Task <TResult> _; pendings.TryRemove(param, out _); } } }); } else { var gates = new ConditionalWeakTable <TParam, AsyncLock>(); return(async(ct, param) => { var gate = gates.GetValue(param, _ => new AsyncLock()); using (await gate.LockAsync(ct)) { return await func(ct, param); } }); } }
/// <summary> /// Gets a dictionary of field metadata created from the properties of the given type. /// </summary> /// <param name="type"></param> /// <param name="fromCache"></param> /// <param name="maxRecusionDepth">The maximum number of levels to recurse down the object's child properties. The default value is 1 (no recursion).</param> /// <returns></returns> public static IEnumerable <ReflectedFieldMetadata> GetFieldsFromType(Type type, bool fromCache = true, int?maxRecursionDepth = null) { string cacheKey = $"{type.AssemblyQualifiedName}:{(fromCache ? 1 : 0)}:{maxRecursionDepth ?? DefaultMaxRecursionDepth}"; if (!fromCache) { return(GetListPropertyInfoInternal(type, maxRecursionDepth)); } return(s_typeCache.GetOrAdd(cacheKey, (key) => { return GetListPropertyInfoInternal(type, maxRecursionDepth); })); }
public CefBrowserExtraData GetExtraData(bool create) { long id = Identifier; if (create) { return(edmap.GetOrAdd(id, v => new CefBrowserExtraData())); } if (edmap.TryGetValue(id, out var val)) { return(val); } return(null); }
/// <summary> /// Creates the specified Context type based on the entity attribute or default configuration of its data source. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entityType">Type of the entity.</param> /// <returns>T.</returns> public T Create <T>(Type entityType) { T context = default(T); var attr = entityType.GetCustomAttribute <UseSharedDataSourceAttribute>(); var dataSourceName = (!string.IsNullOrWhiteSpace(attr?.DataSource)) ? attr.DataSource : SharedDataSource.DefaultDB.ToString(); int contextHash = dataSourceName.GetHashCode(); context = (T)_contextCache.GetOrAdd(contextHash, (hash) => { var factory = (ISharedContextFactory <T>)_serviceLocator.GetNamed <ISharedContextFactory>(dataSourceName.ToString()); return(factory.Get(entityType, dataSourceName)); }); return(context); }
public Tuple <Type, ConstructorInfo, MethodInfo> BuildType(ModuleBuilder moduleBuilder, Type targetType, MethodInfo method, ParameterInfo[] parameters) { Comparer comparer = new Comparer { TargetType = targetType, Method = method, Parameters = parameters }; return(_map.GetOrAdd(comparer, key => { string typeName = comparer.TargetType.Name; typeName += "_" + Guid.NewGuid().ToString("N").ToUpper(); return BuildNewType(moduleBuilder, typeName, comparer.TargetType.Namespace + ".Anonymous", comparer); })); }
public static TParentType CreateTypeObjectFromParent <TParentType, TField>(IScheme <TField> scheme) where TField : IField { try { var schemeKey = string.Join(";", scheme.Keys.OrderBy(x => x)); var instanceType = _proxyTypes.GetOrAdd(schemeKey, (key) => CreateTypeFromParent <TParentType, TField>(scheme)); if (instanceType != null) { var obj = Activator.CreateInstance(instanceType, new object[] { scheme }); return((TParentType)obj); } } catch (Exception ex) { Debug.WriteLine("CreateTypeObjectFromParent<{0}>: {1}", typeof(TParentType).Name, ex.Message); } return(default(TParentType)); }
async public static void TimerCallback(object objt) { while (true) { try { var tcpListen = objt as System.Net.Sockets.TcpListener; var listenList = new List <Task <System.Net.Sockets.TcpClient> >(); tcpListen.Server.UseOnlyOverlappedIO = true; while (tcpListen.Pending()) { listenList.Add(tcpListen.AcceptTcpClientAsync()); } //listenTimer.Change(100, 1); // Let's stop the timer from consuming too many threads bool restart = false; for (int i = 0; i < listenList.Count; i++) { var item = listenList[i]; var listen = await item; System.Threading.Interlocked.Increment(ref clientsConnected); if (item.IsCompleted) { TcpByteAgentHandler tcbah = new TcpByteAgentHandler(new TcpByteTransport(listen), TcpByteAgentHandler.HandlerType.ReceiveHeavy); tcbah.AddCommand(new ChainsAPM.Commands.Common.SendString("")); tcbah.HasData += tcbah_HasDataEvent; tcbah.Disconnected += tcbah_Disconnected; concurrentAgentHandlerList.GetOrAdd(tcbah.GetHashCode(), tcbah); } if (i == listenList.Count - 1 && restart == true) { i = 0; restart = false; } } } catch (Exception) { throw; } finally { } System.Threading.Thread.Sleep(10); } }
public static TypeDescriptor GetDescriptor(Type type) { TypeDescriptor instance; if (!InstanceCache.TryGetValue(type, out instance)) { lock (type) { if (!InstanceCache.TryGetValue(type, out instance)) { instance = new TypeDescriptor(type); InstanceCache.GetOrAdd(type, instance); } } } return(instance); }
public static MemberValueSetter GetMemberValueSetter(MemberInfo memberInfo) { MemberValueSetter setter = null; if (!Cache.TryGetValue(memberInfo, out setter)) { lock (memberInfo) { if (!Cache.TryGetValue(memberInfo, out setter)) { setter = DelegateGenerator.CreateValueSetter(memberInfo); Cache.GetOrAdd(memberInfo, setter); } } } return(setter); }