Пример #1
0
        /// <summary>根据表名和列名生成ID,第一次生成后就不需要再访问数据库,频率高时使用</summary>
        /// <param name="tableName">表名</param>
        /// <param name="colName">列名</param>
        /// <returns></returns>
        public int NewID(IDbAccess iDb, string tableName, string colName)
        {
            string key     = GeneKey(tableName, colName);
            object lockobj = GetLock(tableName, colName);

            lock (lockobj)
            {
                object obj;
                if (!ht_ids.TryGetValue(key, out obj))
                {
                    string str = iDb.GetFirstColumnString(string.Format("select max({0}) from {1}", colName, tableName));
                    if (string.IsNullOrWhiteSpace(str))
                    {
                        obj = 1;
                    }
                    else
                    {
                        obj = int.Parse(str) + 1;
                    }
                    ht_ids.TryAdd(key, obj);
                }
                else
                {
                    obj         = int.Parse(obj.ToString()) + 1;
                    ht_ids[key] = obj;
                }
                return(int.Parse(obj.ToString()));
            }
        }
Пример #2
0
        public static PyObject ImportModule(string name)
        {
            if (!objs.ContainsKey(name))
            {
                IntPtr op = Runtime.PyImport_ImportModule(name);
                if (op == IntPtr.Zero || op == Runtime.PyNone)
                {
                    for (int i = 0; i < 10; i++)
                    {
                        System.Threading.Thread.Sleep(100);
                        Console.WriteLine("-------------------- Import Error TRY(" + i + "): " + name);
                        op = Runtime.PyImport_ImportModule(name);
                        if (op != IntPtr.Zero && op != Runtime.PyNone)
                        {
                            break;
                        }
                    }

                    if (op == IntPtr.Zero || op == Runtime.PyNone)
                    {
                        Console.WriteLine("-------------------- Import Error FINAL: " + name);
                        Runtime.CheckExceptionOccurred();
                    }
                }

                objs.TryAdd(name, new PyObject(op));
            }

            return(objs[name]);
        }
Пример #3
0
        public async Task <bool> AddSagas(IAsyncEnumerable <SagasGroupEntity> sagasGroupEntities)
        {
            await foreach (var sagasGroupEntity in sagasGroupEntities)
            {
                if (!Sagas.ContainsKey(sagasGroupEntity.ServiceName))
                {
                    var bufferBlock = new BufferBlock <SagaEntity>();
                    sagasGroupEntity.SagaEntities.ForEach(m =>
                    {
                        bufferBlock.SendAsync(m);
                    });

                    Sagas.TryAdd(sagasGroupEntity.ServiceName, bufferBlock);
                }
                else
                {
                    // 这里必然为true
                    Sagas.TryGetValue(sagasGroupEntity.ServiceName, out BufferBlock <SagaEntity> bufferBlock);
                    sagasGroupEntity.SagaEntities.ForEach(m =>
                    {
                        bufferBlock.SendAsync(m);
                    });
                }
            }
            return(true);
        }
Пример #4
0
        public RegisteredClient Register(int identity)
        {
            RegisteredClient rc = new RegisteredClient(Guid.NewGuid().ToString(), identity);

            _registrationList.TryAdd(rc.SocketKey, rc);
            return(rc);
        }
Пример #5
0
        /// <summary>
        /// Gets a <see cref="IPropertyRenderer"/> for the specified type.
        /// </summary>
        /// <param name="type">The type that can be rendered by this renderer.</param>
        /// <returns>A <see cref="IPropertyRenderer"/> reference, or null if no renderer could be found.</returns>
        /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="type"/> is null.</exception>
        public IPropertyRenderer GetRenderer(Type type)
        {
#if CONTRACTS_ONLY
            BaitExceptionHelper.Throw();
            return(null);
#else
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (_KnownRenderers.Count == 0)
            {
                return(null);
            }

            IPropertyRenderer retVal = null;

            retVal = GetFromCache(type);
            if (retVal == null)
            {
                retVal = LookupByType(type);
                _CachedRenderers.TryAdd(type, retVal);
            }

            return(retVal);
#endif
        }
Пример #6
0
        public async Task <IActionResult> StarResult(StarSearch search)
        {
            int threads = 4;

            if (ModelState.IsValid)
            {
                search.SearchDays  = Math.Min(search.SearchDays, 14);
                search.Destination = search.Destination.MyTrim();
                search.Origin      = search.Origin.MyTrim();
                if (search.Origin.MyLength() == 3 && search.Destination.MyLength() == 3)
                {
                    var dates = System.Linq.Enumerable.Range(0, search.SearchDays).Select(i => search.OutDate.AddDays(i)).ToList();
                    dates.Shuffle();
                    var res = new System.Collections.Concurrent.ConcurrentDictionary <DateTime, FlysasLib.SearchResult>();
                    await Dasync.Collections.ParallelForEachExtensions.ParallelForEachAsync <DateTime>(dates,
                                                                                                       async date =>
                    {
                        if (!res.ContainsKey(date))    //this looks smart, but doesn't realy save a lot of calls...
                        {
                            var q = new SASQuery
                            {
                                OutDate = date,
                                From    = search.Origin,
                                To      = search.Destination,
                                Adults  = search.Pax,
                                Mode    = SASQuery.SearhMode.STAR
                            };
                            var c = new FlysasLib.SASRestClient();
                            FlysasLib.SearchResult searchResult = await c.SearchAsync(q);

                            if (searchResult.tabsInfo != null && searchResult.tabsInfo.outboundInfo != null)
                            {
                                foreach (var dayWithNoSeats in searchResult.tabsInfo.outboundInfo.Where(tab => tab.points == 0))
                                {
                                    res.TryAdd(dayWithNoSeats.date, null);
                                }
                            }

                            res.TryAdd(date, searchResult);
                        }
                    },
                                                                                                       threads,
                                                                                                       false
                                                                                                       );

                    search.Results = res.Where(r => r.Value?.outboundFlights != null).SelectMany(r => r.Value.outboundFlights).ToList();
                    if (search.MaxLegs > 0)
                    {
                        search.Results = search.Results.Where(r => r.segments.Count() <= search.MaxLegs).ToList();
                    }
                }
                else
                {
                    search.Results = new List <FlysasLib.FlightBaseClass>();
                }
            }
            return(View(nameof(Star), search));
        }
Пример #7
0
        public async Task InvokeMethod_WithAlternateDictionaryNamedArgs()
        {
            var args = new System.Collections.Concurrent.ConcurrentDictionary <string, object>();

            args.TryAdd("a", 4);
            args.TryAdd("b", 6);
            var answer = await _Client.Invoke <int>("add", args).ConfigureAwait(false);

            Assert.AreEqual(10, answer);
        }
Пример #8
0
        public void GDictionaryTest2()
        {
            var m1 = new System.Collections.Concurrent.ConcurrentDictionary <string, object>();

            m1.TryAdd("A", 1);
            m1.TryAdd("B", 2);
            var m2 = ObjectComparer(m1);

            Assert.Equal(m1.Count, m2.Count);
            foreach (var item in m1)
            {
                Assert.Equal(item.Value, m2[item.Key]);
            }
        }
Пример #9
0
        static string GetUrl(string url, string name, string localIP = "127.0.0.1", string vedioResalution = "640*480")
        {
            string outputUrl;

            if (process.TryGetValue(name, out outputUrl))
            {
                return(outputUrl);
            }

            string id = Guid.NewGuid().ToString();

            outputUrl = $"rtmp://{localIP}/mylive/" + name;
            //第三步检测服务器SRS是否正常开启
            string strpath   = System.IO.Directory.GetCurrentDirectory();   //文件名
            string fileName  = @"" + strpath + "\\ffmpeg\\bin\\ffmpeg.exe"; //ffmpeg的绝对路径可以自由更改
            string arguments = " -i " + "\"" + url + "\"" + " -vcodec copy -acodec aac -ar 44100 -strict -2 -ac 1 -f flv -s " + vedioResalution + " \"" + outputUrl + "\"";
            //arguments = "-i " + url + "  -f flv -r 25 -s " + VedioResalution + " -an " + "\"" + outputUrl + "\"";//ffmpeg参数
            dynamic obj = new { name = fileName, arguments = arguments };

            System.Threading.Thread th = new System.Threading.Thread(new ParameterizedThreadStart(ProcessStart));
            th.IsBackground = true;
            th.Start(obj);
            process.TryAdd(name, outputUrl);
            return(outputUrl);
        }
Пример #10
0
 public void CreateObjCreater(Dictionary <string, ColumnType> queryFields)
 {
     #region  EMIT创建
     //var key = typeof(TSource).ToString() + string.Join("-", mapping.Select(b => b.MappingName));
     Delegate dg;
     //缓存处理
     var a = DelegateCache.TryGetValue(selectKey, out dg);
     if (a)
     {
         ObjCreater = (Func <DataContainer, TSource>)dg;
         return;
     }
     else
     {
         if (AnonymousClass)
         {
             ObjCreater = CreateObjectGenerator <TSource>(Constructor);
         }
         else
         {
             ObjCreater = CreateObjectGeneratorEmit <TSource>(Mapping, queryFields);
         }
         DelegateCache.TryAdd(selectKey, ObjCreater);
     }
     #endregion
 }
Пример #11
0
        public static LambdaQuery <T> CreateLambdaQuery <T>(DbContext _dbContext) where T : IModel, new()
        {
            var configBuilder = SettingConfigBuilder.current;
            var _DBType       = _dbContext.DBHelper.CurrentDBType;

            if (_DBType != DBType.MongoDB)
            {
                return(new RelationLambdaQuery <T>(_dbContext));
            }
            var type = typeof(T);
            var a    = mongoQueryCreaters.TryGetValue(type, out object creater);

            if (!a)
            {
                a = configBuilder.LambdaQueryTypeRegister.TryGetValue(DBType.MongoDB, out Type type2);
                if (!a)
                {
                    throw new CRLException("未引用CRL.MongoDB");
                }
                var genericType = type2.MakeGenericType(typeof(T));
                creater = Core.DynamicMethodHelper.CreateCtorFunc <Func <DbContext, LambdaQuery <T> > >(genericType, new Type[] { typeof(DbContext) });
                mongoQueryCreaters.TryAdd(type, creater);
            }
            var func = (Func <DbContext, LambdaQuery <T> >)creater;

            return(func(_dbContext));
        }
Пример #12
0
        /// <summary>
        /// 将组合商品拆分成基础商品信息
        /// </summary>
        public void setProductNum(RequestOrderStatusList m, System.Collections.Concurrent.ConcurrentBag <RequestOrderStatusList> productList, System.Collections.Concurrent.ConcurrentDictionary <string, List <string> > baseProductDictionary)
        {
            var ProductList = this.GetXMProductListByzuheCode(m.PlatformMerchantCode, 508);//判断是否是组合商品,是的话将会拆分成组成商品的基础商品信息
            var erpPlatformMerchantCodelist = new List <string>();

            if (ProductList.Count != 0)
            {
                foreach (var elem in ProductList)
                {
                    var entity = new RequestOrderStatusList();
                    entity.OrderCode            = m.OrderCode;
                    entity.PlatformMerchantCode = elem.PlatformMerchantCode; //料号(商品编码,对应供应商那边)
                    erpPlatformMerchantCodelist.Add(elem.PlatformMerchantCode);
                    productList.Add(entity);
                }
            }
            else
            {
                productList.Add(m);
                //erpPlatformMerchantCodelist.Add(m.PlatformMerchantCode);
            }
            var keyvalue = m.OrderCode + "," + m.PlatformMerchantCode;

            if (!baseProductDictionary.Keys.Contains(keyvalue))
            {
                baseProductDictionary.TryAdd(keyvalue, erpPlatformMerchantCodelist);
            }
        }
Пример #13
0
 private static void AddMemoryCache(CacheItem cacheItem)
 {
     if (cacheItem != null)
     {
         Items.TryAdd(cacheItem.Type + ":" + cacheItem.Key, cacheItem);
     }
 }
Пример #14
0
        public static object GetLocker(string lockname)
        {
            if (string.IsNullOrWhiteSpace(lockname))
            {
                throw new ArgumentException("lockname");
            }
            object obj = null;

            if (_lockerdic.TryGetValue(lockname, out obj))
            {
                return(obj);
            }
            lock (_locker)
            {
                if (_lockerdic.TryGetValue(lockname, out obj))
                {
                    return(obj);
                }

                obj = new object();
                if (_lockerdic.TryAdd(lockname, obj))
                {
                    return(obj);
                }
                throw new Exception("添加锁失败:" + lockname);
            }
        }
Пример #15
0
 public void Add(T1 key, T2 value)
 {
     lock (this)
     {
         if (!_keyValue.TryGetValue(key, out List <T2> result))
         {
             _keyValue.TryAdd(key, new List <T2>()
             {
                 value
             });
         }
         else if (!result.Contains(value))
         {
             result.Add(value);
         }
         if (!_valueKey.TryGetValue(value, out List <T1> result2))
         {
             _valueKey.TryAdd(value, new List <T1>()
             {
                 key
             });
         }
         else if (!result2.Contains(key))
         {
             result2.Add(key);
         }
     }
 }
Пример #16
0
        public static async Task InsertGroupMemberInfo(Model.GetGroupMemberListPackage getGroupMemberListPackage)
        {
            System.Collections.Concurrent.ConcurrentDictionary <int, DB.GroupMemberInfo> dic = new System.Collections.Concurrent.ConcurrentDictionary <int, DB.GroupMemberInfo>();
            var array = getGroupMemberListPackage.data.items.ToArray();

            foreach (var item in array)
            {
                DB.GroupMemberInfo info = new DB.GroupMemberInfo()
                {
                    groupId         = item.groupId,
                    memoInGroup     = item.memoInGroup,//群昵称
                    userId          = item.userId,
                    userName        = item.userName,
                    auditUserId     = item.auditUserId,
                    city            = item.city,
                    createTime      = item.createTime,
                    mobile          = item.mobile,
                    photo           = item.photo,
                    province        = item.province,
                    recommendByUser = item.recommendByUser,
                    sex             = item.sex
                };
                dic.TryAdd(info.userId, info);
            }
            try
            {
                await SDKProperty.SQLiteConn.ExecuteAsync($"delete from GroupMemberInfo where groupId ={getGroupMemberListPackage.data.groupId}");

                await SDKProperty.SQLiteConn.InsertAllAsync(dic.Values);
            }
            catch (Exception)
            {
                await SDKProperty.SQLiteConn.ExecuteAsync($"delete from GroupMemberInfo where groupId ={getGroupMemberListPackage.data.groupId}");
            }
        }
Пример #17
0
 public static void Store(string guid, CacheInfo info)
 {
     while (false == sessionStores.TryAdd(guid, info))
     {
         ;
     }
 }
Пример #18
0
        /// <summary>
        /// 获取自定义Attribute列表
        /// </summary>
        /// <param name="customAttributeProvider"></param>
        /// <param name="type">特性类型, instance is type。</param>
        /// <param name="inherit">如果为 true,则指定还在 element 的祖先中搜索自定义特性。</param>
        /// <returns></returns>
        public static System.Collections.IList GetCustomAttributes(
#if !net20
            this
#endif
            System.Reflection.ICustomAttributeProvider customAttributeProvider, System.Type type, bool inherit)
        {
            if (customAttributeProvider == null || type == null)
            {
                return(CreateList(type));
            }

            System.Collections.IList list;
            string key = string.Concat(GetKeyBefore(customAttributeProvider), "_", type.AssemblyQualifiedName);

            if (!_list_key.TryGetValue(key, out list))
            {
                ThreadHelper.Block(_list_key, () => {
                    if (!_list_key.TryGetValue(key, out list))
                    {
                        list = CreateList(type);
                        foreach (var item in customAttributeProvider.GetCustomAttributes(inherit))
                        {
                            if (item.GetType() == type || TypeExtensions.IsInheritFrom(item.GetType(), type))
                            {
                                list.Add(item);
                            }
                        }
                        _list_key.TryAdd(key, list);
                    }
                });
            }

            return(list);
        }
Пример #19
0
        public long OpenPanel()
        {
            var keyValue = System.Threading.Interlocked.Increment(ref _key);

            _tasks.TryAdd(_key, new ProcessingTask());
            return(keyValue);
        }
Пример #20
0
        public void ReadWriteTest()
        {
            var options = new HttpApiOptions().JsonSerializeOptions;

            var obj1 = new FormatModel {
                Age = 18, Name = "老九"
            };
            var formatter = new WebApiClientCore.Serialization.JsonSerializer();

            using var buffer = new BufferWriter <byte>();
            formatter.Serialize(buffer, obj1, options);
            var json = buffer.GetWrittenSpan().ToArray();
            var obj2 = formatter.Deserialize(json, typeof(FormatModel), options);

            Assert.True(obj1.Equals(obj2));

            var dic = new System.Collections.Concurrent.ConcurrentDictionary <string, object>();

            dic.TryAdd("Key", "Value");

            buffer.Clear();

            formatter.Serialize(buffer, dic, options);
            var json2 = Encoding.UTF8.GetString(buffer.GetWrittenSpan().ToArray());

            Assert.Contains("key", json2);
        }
Пример #21
0
 public void AddUser(string UserId)
 {
     if (!string.IsNullOrEmpty(UserId))
     {
         _list.TryAdd(UserId, UserId);
     }
 }
Пример #22
0
        public void MultiThreadProxy()
        {
            HttpClientPool pool       = new HttpClientPool();
            var            spider     = new DefaultSpider();
            var            downloader = new HttpClientDownloader();

            System.Collections.Concurrent.ConcurrentDictionary <HttpClientElement, int> tonggi = new System.Collections.Concurrent.ConcurrentDictionary <HttpClientElement, int>();
            Parallel.For(0, 1000, new ParallelOptions {
                MaxDegreeOfParallelism = 1
            }, (i) =>
            {
                var port  = i % 10;
                var proxy = new UseSpecifiedUriWebProxy(new Uri($"http://192.168.10.1:{port}"), null, false);
                var item  = pool.GetHttpClient(spider, downloader, new System.Net.CookieContainer(), proxy, null);

                if (tonggi.ContainsKey(item))
                {
                    tonggi[item] = tonggi[item] + 1;
                }
                else
                {
                    tonggi.TryAdd(item, 1);
                }
            });

            Assert.Equal(10, tonggi.Count);
            foreach (var pair in tonggi)
            {
                Assert.Equal(100, pair.Value);
            }
        }
Пример #23
0
        /// <summary>
        /// Gets an interface to the <see cref="ContainerPropertyBag{TContainer}"/> for the given type.
        /// </summary>
        /// <remarks>
        /// The returned <see cref="IPropertyBag"/> can be used to get the strongly typed generic using the <see cref="IPropertyBag.Accept"/> method.
        /// </remarks>
        /// <param name="type">The container type to resolve the property bag for.</param>
        /// <returns>The resolved property bag.</returns>
        internal static IPropertyBag GetPropertyBag(Type type)
        {
            if (s_PropertyBags.TryGetValue(type, out var propertyBag))
            {
                return(propertyBag);
            }

            if (!RuntimeTypeInfoCache.IsContainerType(type))
            {
                return(null);
            }

            if (type.IsInterface || type.IsAbstract)
            {
                return(null);
            }

            if (null != s_PropertyBagProvider)
            {
                propertyBag = s_PropertyBagProvider.CreatePropertyBag(type);

                if (null == propertyBag)
                {
                    s_PropertyBags.TryAdd(type, null);
                }
                else
                {
                    propertyBag.Register();
                    return(propertyBag);
                }
            }

            return(null);
        }
Пример #24
0
        public TValue GetOrAdd(TKey key, Func <TValue> valueFactory, out bool added)
        {
            added = false;

            var value       = default(TValue);
            var newValue    = default(TValue);
            var hasNewValue = false;

            while (true)
            {
                if (_map.TryGetValue(key, out value))
                {
                    break;
                }

                if (!hasNewValue)
                {
                    newValue    = valueFactory();
                    hasNewValue = true;
                }

                if (_map.TryAdd(key, newValue))
                {
                    added = true;
                    value = newValue;
                    break;
                }
            }

            return(value);
        }
Пример #25
0
 public QueryInfo(bool anonymousClass, string _selectKey, IEnumerable <Attribute.FieldMapping> mapping = null, ConstructorInfo constructor = null)
 {
     selectKey      = typeof(TSource) + _selectKey;
     mapping        = mapping ?? new List <Attribute.FieldMapping>();
     Mapping        = mapping;
     AnonymousClass = anonymousClass;
     #region  EMIT创建
     //var key = typeof(TSource).ToString() + string.Join("-", mapping.Select(b => b.MappingName));
     Delegate dg;
     //缓存处理
     var a = DelegateCache.TryGetValue(selectKey, out dg);
     if (a)
     {
         ObjCreater = (Func <DataContainer, TSource>)dg;
         return;
     }
     else
     {
         if (anonymousClass)
         {
             ObjCreater = CreateObjectGenerator <TSource>(constructor);
         }
         else
         {
             ObjCreater = CreateObjectGeneratorEmit <TSource>(mapping);
         }
         DelegateCache.TryAdd(selectKey, ObjCreater);
     }
     #endregion
 }
Пример #26
0
 public void AddObserver <T>(Action <T> handler) where T : class
 {
     if (!D_.TryAdd(typeof(T), arg => handler((T)arg)))
     {
         throw new InvalidOperationException();
     }
 }
Пример #27
0
        /// <summary>
        /// 初始缓存信息
        /// </summary>
        /// <param name="key"></param>
        /// <param name="minute">过期时间,单位分</param>
        /// <param name="handler">委托</param>
        public static T Init <T>(string key, double minute, GetDataHandler <T> handler)
        {
            var a         = caches.TryGetValue(key, out CacheObj data);
            var doHandler = false;

            if (!a)
            {
                doHandler = true;
            }
            if (a && data.expTime < DateTime.Now)
            {
                doHandler = true;
            }
            if (!doHandler)
            {
                return((T)data.data);
            }
            var obj = handler();

            data = new CacheObj()
            {
                data = obj, expTime = DateTime.Now.AddMinutes(minute)
            };
            caches.TryRemove(key, out CacheObj obj2);
            caches.TryAdd(key, data);
            return(obj);
        }
        public async Task <bool> ValidateClient(string clientId, string clientSecret)
        {
            string dict_clientSecret;

            if (dictClient.TryGetValue(clientId, out dict_clientSecret) && dict_clientSecret == clientSecret)
            {
                return(true);
            }
            else
            {
                return(await Task.Run <bool>(() => {
                    AuthClientInfoEntity entity = new AuthClientInfoEntity();
                    entity.ClientId = clientId;
                    entity.ClientSecret = clientSecret;
                    OQL q = OQL.From(entity)
                            .Select(entity.ClientId)
                            .Where(entity.ClientId, entity.ClientSecret)
                            .END;
                    AuthDbContext context = new AuthDbContext();
                    AuthClientInfoEntity dbEntity = context.QueryObject <AuthClientInfoEntity>(q);
                    if (dbEntity != null)
                    {
                        dictClient.TryAdd(clientId, clientSecret);
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }));
            }
        }
Пример #29
0
        static int _m_TryAdd(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);



                {
                    long  _key   = LuaAPI.lua_toint64(L, 2);
                    ulong _value = LuaAPI.lua_touint64(L, 3);

                    bool gen_ret = gen_to_be_invoked.TryAdd(
                        _key,
                        _value);
                    LuaAPI.lua_pushboolean(L, gen_ret);



                    return(1);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
Пример #30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="folder">保存目录</param>
        /// <param name="name">文件名</param>
        public FileLogger(string folder, string name)
        {
            _SavePath = folder;
            if (!string.IsNullOrEmpty(name))
            {
                name = name.Replace("/", "_").Replace("\\", "_");
                if (System.IO.Directory.Exists(_SavePath) == false)
                {
                    Directory.CreateDirectory(_SavePath);
                }

                this.Name = name;

                if (Dict.TryGetValue(this.Name, out _fileItem) == false)
                {
                    Dict.TryAdd(this.Name, new FileItem());
                    _fileItem = Dict[this.Name];

                    lock (_fileItem)
                    {
                        if (_fileItem.File == null)
                        {
                            createFileStream();
                        }
                    }
                }
            }
        }
Пример #31
0
        public static void Init()
        {
            apis = new System.Collections.Concurrent.ConcurrentDictionary<string, Type>();

            var ts = typeof(SdkSetup).Assembly.GetTypes();

            foreach (var t in ts)
            {
                var at = t.GetCustomAttribute<ApipathAttribute>(false);

                if (at == null)
                    continue;
                apis.TryAdd(at.Path, t);
            }
        }
Пример #32
0
        public void Lock_Contend_LockDelay()
        {
            var client = new ConsulClient();

            const string keyName = "test/lock/contendlockdelay";

            const int contenderPool = 3;

            var acquired = new System.Collections.Concurrent.ConcurrentDictionary<int, bool>();
            using (var cts = new CancellationTokenSource())
            {
                cts.CancelAfter((contenderPool + 1) * (int)Lock.DefaultLockWaitTime.TotalMilliseconds);

                Parallel.For(0, contenderPool, new ParallelOptions { MaxDegreeOfParallelism = contenderPool, CancellationToken = cts.Token }, (v) =>
                {
                    var lockKey = (Lock)client.CreateLock(keyName);
                    lockKey.Acquire(CancellationToken.None);
                    if (lockKey.IsHeld)
                    {
                        Assert.True(acquired.TryAdd(v, lockKey.IsHeld));
                        client.Session.Destroy(lockKey.LockSession);
                    }
                });
            }
            for (var i = 0; i < contenderPool; i++)
            {
                bool didContend = false;
                if (acquired.TryGetValue(i, out didContend))
                {
                    Assert.True(didContend);
                }
                else
                {
                    Assert.True(false, "Contender " + i.ToString() + " did not acquire the lock");
                }
            }
        }
Пример #33
0
        public void Lock_ContendFast()
        {
            var client = new ConsulClient();

            const string keyName = "test/lock/contend";
            const int contenderPool = 10;

            var acquired = new System.Collections.Concurrent.ConcurrentDictionary<int, bool>();
            using (var cts = new CancellationTokenSource())
            {
                cts.CancelAfter(contenderPool * (int)Lock.DefaultLockWaitTime.TotalMilliseconds);

                Parallel.For(0, contenderPool, new ParallelOptions { MaxDegreeOfParallelism = contenderPool, CancellationToken = cts.Token }, (v) =>
                {
                    var lockKey = client.CreateLock(keyName);
                    lockKey.Acquire(CancellationToken.None);
                    Assert.True(acquired.TryAdd(v, lockKey.IsHeld));
                    if (lockKey.IsHeld)
                    {
                        lockKey.Release();
                    }
                });
            }

            for (var i = 0; i < contenderPool; i++)
            {
                if (acquired[i])
                {
                    Assert.True(acquired[i]);
                }
                else
                {
                    Assert.True(false, "Contender " + i.ToString() + " did not acquire the lock");
                }
            }
        }
Пример #34
0
        private void RefreshListViewSimilarDrinks(Drink[] similarDrinksArray)
        {
            lv_SimilarDrinks.BeginUpdate();

            lv_SimilarDrinks.Items.Clear();
            lv_SimilarDrinks.LargeImageList.Images.Clear();

            System.Collections.Concurrent.ConcurrentDictionary<int, Image> dictImages = new System.Collections.Concurrent.ConcurrentDictionary<int, Image>();

            System.Threading.Tasks.Parallel.ForEach( similarDrinksArray, drink =>
            {
                dictImages.TryAdd(drink.ID,GetDrinkImage(drink).ResizeImage(SIMILAR_DRINK_IMAGE_SIZE));
            });

            foreach(Drink drink in similarDrinksArray)
            {
                lv_SimilarDrinks.LargeImageList.Images.Add(drink.ID.ToString(),dictImages[drink.ID]);
                ListViewItem lvi = new ListViewItem(drink.Name);
                lvi.Tag = drink.Url;
                lvi.ImageKey = drink.ID.ToString();
                lv_SimilarDrinks.Items.Add(lvi);
            }

            /*
            for (int i = 0; i < similarDrinksArray.Length; i++)
            {
                lv_SimilarDrinks.LargeImageList.Images.Add(GetDrinkImage(similarDrinksArray[i]).ResizeImage(SIMILAR_DRINK_IMAGE_SIZE));
                ListViewItem lvi = new ListViewItem(similarDrinksArray[i].Name);
                lvi.Tag = similarDrinksArray[i].Url;
                lvi.ImageIndex = i;

                lv_SimilarDrinks.Items.Add(lvi);
            }
            */

            lv_SimilarDrinks.EndUpdate();
        }
Пример #35
0
        private async Task BatchSendAsync()
        {
            var outstandingSendTasks = new System.Collections.Concurrent.ConcurrentDictionary<Task, Task>();
            while (_asyncCollection.IsCompleted == false || _asyncCollection.Count > 0)
            {
                List<TopicMessage> batch = null;

                try
                {
                    try
                    {
                        await _asyncCollection.OnHasDataAvailable(_stopToken.Token).ConfigureAwait(false);

                        batch = await _asyncCollection.TakeAsync(BatchSize, BatchDelayTime, _stopToken.Token).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException ex)
                    {
                        //TODO log that the operation was canceled, this only happens during a dispose
                    }

                    if (_asyncCollection.IsCompleted && _asyncCollection.Count > 0)
                    {
                        batch = batch ?? new List<TopicMessage>(_asyncCollection.Count);

                        //Drain any messages remaining in the queue and add them to the send batch
                        batch.AddRange(_asyncCollection.Drain());
                    }

                    //we want to fire the batch without blocking and then move on to fire another one
                    var sendTask = ProduceAndSendBatchAsync(batch, _stopToken.Token);

                    outstandingSendTasks.TryAdd(sendTask, sendTask);

                    var sendTaskCleanup = sendTask.ContinueWith(result =>
                    {
                        if (result.IsFaulted && batch != null)
                        {
                            batch.ForEach(x => x.Tcs.TrySetException(result.ExtractException()));
                        }

                        //TODO add statistics tracking
                        outstandingSendTasks.TryRemove(sendTask, out sendTask);
                    });

                }
                catch (Exception ex)
                {
                    if (batch != null)
                    {
                        batch.ForEach(x => x.Tcs.TrySetException(ex));
                    }
                }
            }

            var referenceToOutstanding = outstandingSendTasks.Values.ToList();
            if (referenceToOutstanding.Count > 0)
            {
                await Task.WhenAll(referenceToOutstanding).ConfigureAwait(false);
            }
        }