} // End Sub CertificateFileChanged

        public static System.Security.Cryptography.X509Certificates.X509Certificate2 ServerCertificateSelector(
            System.Collections.Concurrent.ConcurrentDictionary <string, CertHackStore> certs
            , Microsoft.AspNetCore.Connections.ConnectionContext connectionContext
            , string name)
        {
            if (certs != null && certs.Count > 0)
            {
                // return certs.GetEnumerator().Current.Value;
                // return System.Linq.Enumerable.FirstOrDefault(certs);
                foreach (System.Collections.Generic.KeyValuePair <string, CertHackStore> thisCert in certs)
                {
                    System.Console.WriteLine("SNI Name: {0}", name);

                    return(thisCert.Value.Certificate);
                } // Next thisCert
            }     // End if (certs != null && certs.Count > 0)


            // CertHackStore cert;
            // if (name != null && certs.TryGetValue(name, out cert))
            // {
            //     return cert.NewCertificate;
            // }

            throw new System.IO.InvalidDataException("No certificate for name \"" + name + "\".");
        } // End Function ServerCertificateSelector
 public Manager(Uri uri, ManagerOptions opts)
 {
     if (opts == null)
     {
         opts = new ManagerOptions();
     }
     if (opts.Path == null)
     {
         opts.Path = "/socket.io";
     }
     this.Options    = opts;
     this.Nsps       = new System.Collections.Concurrent.ConcurrentDictionary <string, Socket>();
     this.Subs       = new Queue <On.IHandle>();
     this.TasksQueue = new Queue <TaskWorker>();
     this.Reconnection(opts.Reconnection);
     this.ReconnectionAttempts(opts.ReconnectionAttempts != 0 ? opts.ReconnectionAttempts : int.MaxValue);
     this.ReconnectionDelay(opts.ReconnectionDelay != 0 ? opts.ReconnectionDelay : 1000);
     this.ReconnectionDelayMax(opts.ReconnectionDelayMax != 0 ? opts.ReconnectionDelayMax : 5000);
     this.Timeout(opts.Timeout < 0 ? 20000 : opts.Timeout);
     this.ReadyState   = ReadyStateEnum.CLOSED;
     this.Uri          = uri;
     this.Connected    = 0;
     this.Attempts     = 0;
     this.Encoding     = false;
     this.PacketBuffer = new List <Packet>();
     this.Encoder      = new Parser.Encoder();
     this.Decoder      = new Parser.Decoder();
     this.AutoConnect  = opts.AutoConnect;
     if (AutoConnect)
     {
         Open();
     }
 }
        public async Task Semaphore_ContendFast()
        {
            const string keyName       = "test/semaphore/contend";
            const int    contenderPool = 15;

            var acquired = new System.Collections.Concurrent.ConcurrentDictionary <int, bool>();

            var tasks = new List <Task>();

            for (var i = 0; i < contenderPool; i++)
            {
                var v = i;
                tasks.Add(Task.Run(async() =>
                {
                    var semaphore = _client.Semaphore(keyName, 2);
                    await semaphore.Acquire(CancellationToken.None);
                    acquired[v] = semaphore.IsHeld;
                    await semaphore.Release();
                }));
            }

            await TimeoutUtils.WithTimeout(Task.WhenAll(tasks));

            for (var i = 0; i < contenderPool; i++)
            {
                Assert.True(acquired.ContainsKey(i), $"Contender {i} did not acquire the lock");
                Assert.True(acquired[i], $"IsHeld was false for contender {i}");
            }
        }
Example #4
0
        public void ConcurrentDict_GetOrSet()
        {
            var dict = new System.Collections.Concurrent.ConcurrentDictionary <int, string>();

            dict.GetOrSet(3, () => "bob");
            Assert.Equal("bob", dict.GetValueOrDefault(3));
        }
 ConfigStore()
 {
     LastManifests        = new Dictionary <uint, ulong>();
     SentryData           = new Dictionary <string, byte[]>();
     ContentServerPenalty = new System.Collections.Concurrent.ConcurrentDictionary <string, int>();
     LoginKeys            = new Dictionary <string, string>();
 }
Example #6
0
        } // End Sub ListenAnyIP

        public static void UseHttps(
            System.Collections.Concurrent.ConcurrentDictionary <string, System.Security.Cryptography.X509Certificates.X509Certificate2> certs
            , Microsoft.AspNetCore.Server.Kestrel.Https.HttpsConnectionAdapterOptions httpsOptions)
        {
            System.Security.Cryptography.X509Certificates.X509Certificate2 localhostCert = Microsoft.AspNetCore.Server.Kestrel.Https.CertificateLoader.LoadFromStoreCert(
                "localhost", "My", System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser,
                allowInvalid: true);

            System.Security.Cryptography.X509Certificates.X509Certificate2 exampleCert = Microsoft.AspNetCore.Server.Kestrel.Https.CertificateLoader.LoadFromStoreCert(
                "example.com", "My", System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser,
                allowInvalid: true);

            System.Security.Cryptography.X509Certificates.X509Certificate2 subExampleCert = Microsoft.AspNetCore.Server.Kestrel.Https.CertificateLoader.LoadFromStoreCert(
                "sub.example.com", "My", System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser,
                allowInvalid: true);

            certs["localhost"]       = localhostCert;
            certs["example.com"]     = exampleCert;
            certs["sub.example.com"] = subExampleCert;


            httpsOptions.ServerCertificateSelector =
                delegate(Microsoft.AspNetCore.Connections.ConnectionContext connectionContext, string name)
            {
                return(ServerCertificateSelector(certs, connectionContext, name));
            }
            ;
        } // End Sub UseHttps
        static void Main(string[] args)
        {
            Console.WriteLine("Environment has {0} processors", Environment.ProcessorCount);
            //results = new Dictionary<string, List<Tuple<string, int, ProgramAttributes, BoogieResult, int>>>();
            results = new System.Collections.Concurrent.ConcurrentDictionary<string, SortedDictionary<int, Tuple<string, ProgramAttributes, BoogieResult, int>>>();
            benchmarks = new List<Tuple<string, string, string, string>>();

            //all benchmark options should be in options.cs to avoid changes to this file except for logic changes
            Options.CollectBenchmarks(args, ref benchmarks);

            if (args.Any(x => x.Contains("/time:")))
            {
                string s = args.FirstOrDefault(x => x.Contains("/time:"));
                string[] separators = {":"};
                Options.timeoutPerProcess = Int32.Parse(s.Split(separators, StringSplitOptions.RemoveEmptyEntries)[1]);
            }

            Stopwatch benchmarkStopwatch = new Stopwatch();
            benchmarkStopwatch.Start();
            Tuple<int, int, int> stats = RunBenchmarks(benchmarks,
                args.Contains("/option:norun"),
                args.Contains("/option:splitmemory"),
                args.Contains("/option:optimizestore"),
                args.Contains("/option:optimizeload"));
            benchmarkStopwatch.Stop();

            if (!args.Contains("/option:norun"))
            {
                GenerateResultOutput(stats, benchmarkStopwatch.ElapsedMilliseconds / 1000);
            }
            resultFileNameWriter.Close();
        }
Example #8
0
        public void SerializeTest()
        {
            var obj1 = new FormatModel {
                Age = 18, Name = "laojiu"
            };
            var formatter = new KeyValueFormatter();
            var kvs       = formatter.Serialize("pName", obj1, null)
                            .ToDictionary(item => item.Key, item => item.Value);

            Assert.True(kvs.Count == 2);
            Assert.True(kvs["Name"] == "laojiu");
            Assert.True(kvs["Age"] == "18");


            kvs = formatter.Serialize("pName", 30, null)
                  .ToDictionary(item => item.Key, item => item.Value);

            Assert.True(kvs.Count == 1);
            Assert.True(kvs["pName"] == "30");



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

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

            var options = HttpApiOptions.CreateDefaultJsonOptions();
            var kvs2    = formatter.Serialize("dic", dic, options);

            Assert.True(kvs2.First().Key == "key");


            Assert.True(formatter.Serialize("null", null, null).Any());
        }
Example #9
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);
        }
Example #10
0
        protected async Task <(bool success, AutomationElement elem)> Awaiter_WaitAsync(
            WaitersDictionary waiters,
            Func <AutomationElement, bool> filter,
            int timeOut)
        {
            AsyncAutoResetEvent ev = new AsyncAutoResetEvent(false);

            ValueTuple <AutomationElement, AsyncAutoResetEvent> awaiterData = (null, ev);

            waiters[filter] = awaiterData;

            var cts  = new CancellationTokenSource(timeOut);
            var task = ev.WaitAsync(cts.Token);

            await task;

            cts.Dispose();

            waiters.TryRemove(filter,
                              out awaiterData);

            if (task.IsCanceled)
            {
                return(false, null);
            }

            var ret = awaiterData.Item1;

            return(true, ret);
        }
        public async Task Lock_ContendWait()
        {
            const string keyName       = "test/lock/contendwait";
            const int    contenderPool = 3;

            var acquired = new System.Collections.Concurrent.ConcurrentDictionary <int, bool>();

            var tasks = new List <Task>();

            for (var i = 0; i < contenderPool; i++)
            {
                var v = i;
                acquired[v] = false;
                tasks.Add(Task.Run(async() =>
                {
                    var lockKey = _client.CreateLock(keyName);
                    await lockKey.Acquire(CancellationToken.None);
                    acquired[v] = lockKey.IsHeld;
                    if (lockKey.IsHeld)
                    {
                        await Task.Delay(1000);
                        await lockKey.Release();
                    }
                }));
            }

            await TimeoutUtils.WithTimeout(Task.WhenAll(tasks));

            for (var i = 0; i < contenderPool; i++)
            {
                Assert.True(acquired[i], "Contender " + i.ToString() + " did not acquire the lock");
            }
        }
Example #12
0
        static int _m_ContainsKey(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);

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



                    return(1);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
Example #13
0
 public PalaceInfoManager(ILogger <PalaceInfoManager> logger,
                          Configuration.PalaceServerSettings palaceServerSettings)
 {
     this.Logger = logger;
     this.PalaceServerSettings = palaceServerSettings;
     _palaceInfoDictionary     = new System.Collections.Concurrent.ConcurrentDictionary <string, Models.PalaceInfo>();
 }
Example #14
0
        static int _m_TryUpdate(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 _newValue        = LuaAPI.lua_touint64(L, 3);
                    ulong _comparisonValue = LuaAPI.lua_touint64(L, 4);

                    bool gen_ret = gen_to_be_invoked.TryUpdate(
                        _key,
                        _newValue,
                        _comparisonValue);
                    LuaAPI.lua_pushboolean(L, gen_ret);



                    return(1);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
Example #15
0
        public T Spawn <T, TState>(TState state, System.Func <TState, T> constructor, System.Action <T> destructor = null) where T : class
        {
            if (Pools.isActive == false)
            {
                var instance = constructor.Invoke(state);
                PoolInternalBaseThread.CallOnSpawn(instance, null);
                return(instance);
            }

            var type = typeof(T);

            if (this.pool.TryGetValue(type, out var pool) == true)
            {
                return((T)pool.Spawn());
            }

            pool = new PoolInternalThread <T, TState>(type, state, constructor, destructor);
            if (this.pool.TryAdd(type, pool) == true)
            {
                return((T)pool.Spawn());
            }

            if (this.pool.TryGetValue(type, out pool) == true)
            {
                return((T)pool.Spawn());
            }

            throw new System.Exception("Spawn failed");
        }
Example #16
0
 static ExcelTools()
 {
     // Cache Column Maps
     excelColMap = new System.Collections.Concurrent.ConcurrentDictionary<uint, string>();
     for (uint i = 1; i < 250; i++)
         GetExcelCol(i);
 }
Example #17
0
        public void OnStart()
        {
            OnlineUsers = new System.Collections.Concurrent.ConcurrentDictionary <User, string>();
            //https://github.com/Olivine-Labs/Alchemy-Websockets
            //https://docs.supersocket.net/v2-0/en-US/Get-the-connected-event-and-closed-event-of-a-connection
            // Initialize the server on port 5000, accept any IPs, and bind events.
            aServer = new WebSocketServer(5000, System.Net.IPAddress.Any)
            {
                OnReceive    = OnReceive,
                OnSend       = OnSend,
                OnConnected  = OnConnect,
                OnDisconnect = OnDisconnect,
                TimeOut      = new TimeSpan(0, 5, 0)
            };

            if (webThread == null)
            {
                webThread = new System.Threading.Thread(new System.Threading.ThreadStart(StartWebSocket));
                webThread.IsBackground = true;
                webThread.SetApartmentState(System.Threading.ApartmentState.STA);
            }
            webThread.Start();

            timer         = new System.Timers.Timer(30000);//создаём объект таймера
            timer.Enabled = true;
            timer.Start();
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            AddInfo("timer is running...");
        }
        public static void UpdateConfiguration(HttpConfiguration configuration)
        {
            var repo = ConditionalLinkGeneration_ProductsController.Repository;

            repo[typeof(Product)] = new System.Collections.Concurrent.ConcurrentDictionary <int, Product>();
            var productRepo = repo[typeof(Product)];

            productRepo.TryAdd(1, new Product
            {
                ID     = 1,
                Name   = "Product 1",
                Family = new ProductFamily
                {
                    ID       = 1,
                    Name     = "Product Family 1",
                    Supplier = new Supplier
                    {
                        ID   = 1,
                        Name = "Supplier 1"
                    }
                }
            });

            configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            configuration.EnableODataSupport(GetImplicitEdmModel());
        }
Example #19
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
                    {
                        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);
            }
        }
Example #20
0
 public City(
     double dimensionX = 100, double dimensionY = 100, int cellSize = 1
     )
 {
     _dimensionX = Convert.ToInt32(dimensionX); _dimensionY = Convert.ToInt32(dimensionY);
     _StringCity = new System.Collections.Concurrent.ConcurrentDictionary <Mars.Interfaces.Environment.Position, string>();
     _RealCity   = new System.Collections.Concurrent.ConcurrentDictionary <Mars.Interfaces.Environment.Position, double>();
 }
Example #21
0
 public ProductRepository()
 {
     dbTableMock = new System.Collections.Concurrent.ConcurrentDictionary <Guid, Product>();
     foreach (var product in products)
     {
         dbTableMock.TryAdd(product.Id, product);
     }
 }
Example #22
0
        //public IToCommunication DefaultParseToCommunication =?

        /// <summary>
        /// 根据程序级加载逻辑处理组件
        /// </summary>
        /// <param name="service">当前服务运行服务</param>
        /// <param name="assembly">程序集</param>
        /// <returns>逻辑处理组件</returns>
        public virtual IEnumerable <ILogicWork> LoadAssembly(BaseService service, System.Reflection.Assembly assembly)
        {
            if (LogicDic == null)
            {
                LogicDic = new System.Collections.Concurrent.ConcurrentDictionary <string, ILogicWork>();
            }

            if (SubscribeDic == null)
            {
                SubscribeDic = new System.Collections.Concurrent.ConcurrentDictionary <string, List <ILogicWork> >();
            }

            if (ParseToLogic == null)
            {
                ParseToLogic = new System.Collections.Concurrent.ConcurrentDictionary <string, IToLogic>();
            }

            if (ParseToCommunication == null)
            {
                ParseToCommunication = new System.Collections.Concurrent.ConcurrentDictionary <string, IToCommunication>();
            }

            foreach (var logic in Register.ReflectInstance <ILogicWork>(assembly))
            {
                logic.Service           = service;
                LogicDic[logic.FindKey] = logic;
                if (logic.SubscribeList == null)
                {
                    continue;
                }
                foreach (var findkey in logic.SubscribeList)
                {
                    if (!SubscribeDic.ContainsKey(findkey))
                    {
                        SubscribeDic[findkey] = new List <ILogicWork>();
                    }
                    SubscribeDic[findkey].Add(logic);
                }
            }

            foreach (var parse in Register.ReflectInstance <IToLogic>(assembly))
            {
                parse.Service = service;
                ParseToLogic[parse.FindKey] = parse;
            }

            DefaultParseLogic = new MsgToLogic {
                Service = service
            };

            foreach (var parse in Register.ReflectInstance <IToCommunication>(assembly))
            {
                parse.Service = service;
                ParseToCommunication[parse.FindKey] = parse;
            }

            return(LogicDic.Values.ToList());
        }
Example #23
0
        /// <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();
        }
Example #24
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));
        }
Example #25
0
 public void Clear()
 {
     foreach (var item in this.pool)
     {
         item.Value.Clean();
     }
     this.pool.Clear();
     this.pool = null;
 }
Example #26
0
 /// <summary>
 /// 启动队列
 /// </summary>
 /// <param name="queue">队列</param>
 protected virtual void OnRunQueue(ICommunicationQueue queue)
 {
     queue.Initialize();
     if (RunQueueDic == null)
     {
         RunQueueDic = new System.Collections.Concurrent.ConcurrentDictionary <string, ICommunicationQueue>();
     }
     RunQueueDic[queue.FindKey] = queue;
 }
Example #27
0
 /// <summary>
 /// Create a message sender to service bus
 /// </summary>
 /// <param name="entityName">Queue Name</param>
 /// <param name="connectionStringName">Connection string name to use to look for the connection string in the settings file</param>
 /// <param name="settingData">Configuration data of blob storage hosting messge</param>
 /// <param name="serializer">Object used to serialize message</param>
 public BaseConnector(string entityName, string connectionStringName,
                      StorageSettingData settingData,
                      IMessageSerializer serializer)
     : this(entityName, connectionStringName)
 {
     Clients            = new System.Collections.Concurrent.ConcurrentDictionary <string, TClient>();
     CurrentSettingData = settingData;
     MessageSerializer  = serializer;
 }
Example #28
0
 ConfigStore()
 {
     DownloadRecord       = new List <DownloadRecord>();
     SentryData           = new Dictionary <string, byte[]>();
     ContentServerPenalty = new System.Collections.Concurrent.ConcurrentDictionary <string, int>();
     LoginKeys            = new Dictionary <string, string>();
     LastManifests        = new Dictionary <uint, ulong>();
     StoredCookies        = new Dictionary <string, string>();
 }
Example #29
0
 /// <summary>
 /// Tries to the remove an item with the specified key from this dictionary.
 /// </summary>
 public static K TryRemove <T, K>(this System.Collections.Concurrent.ConcurrentDictionary <T, K> @this, T key)
 {
     if (@this.TryRemove(key, out var result))
     {
         return(result);
     }
     else
     {
         return(default);
Example #30
0
        public Module_RPC(AllPet.Common.ILogger logger, Newtonsoft.Json.Linq.JObject configJson) : base(true)
        {
            this.logger = logger;
            this.config = new Config_Module(configJson);
            this.server = new http.server.httpserver();

            this.recvRPC = new System.Collections.Concurrent.ConcurrentDictionary <int, MessagePackObject?>();
            this.RPCID   = 0;
        }
Example #31
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        public TypeRendererMap() : this(null)
        {
#if CONTRACTS_ONLY
            BaitExceptionHelper.Throw();
#else
            _KnownRenderers  = new System.Collections.Concurrent.ConcurrentDictionary <Type, IPropertyRenderer>();
            _CachedRenderers = new System.Collections.Concurrent.ConcurrentDictionary <Type, IPropertyRenderer>();
#endif
        }
Example #32
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);
            }
        }
        public void Semaphore_ContendFast()
        {
            var client = new ConsulClient();

            const string keyName = "test/semaphore/contend";
            const int contenderPool = 15;

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

                Parallel.For(0, contenderPool, new ParallelOptions { MaxDegreeOfParallelism = contenderPool, CancellationToken = cts.Token }, (v) =>
                {
                    var semaphore = client.Semaphore(keyName, 2);
                    semaphore.Acquire(CancellationToken.None);
                    acquired[v] = semaphore.IsHeld;
                    semaphore.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");
                }
            }
        }
Example #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();
        }
Example #35
0
 private State()
 {
     Clients = new System.Collections.Concurrent.ConcurrentDictionary<string, Client>();
 }
Example #36
0
 public Administrator()
 {
     MemetoDictionary = new System.Collections.Concurrent.ConcurrentDictionary<string, Memento>();
 }
 ConfigStore()
 {
     LastManifests = new Dictionary<uint, ulong>();
     SentryData = new Dictionary<string, byte[]>();
     ContentServerPenalty = new System.Collections.Concurrent.ConcurrentDictionary<string, int>();
 }
 public SqLiteHoldConnection()
 {
     _connections = new System.Collections.Concurrent.ConcurrentDictionary<string, SQLiteConnection>();
 }
Example #39
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);
            }
        }
 static Correlation()
 {
   syncs = new System.Collections.Concurrent.ConcurrentDictionary<uint, System.Threading.ManualResetEvent>();
 }
 public Manager(Uri uri, Options opts)
 {
     if (opts == null)
     {
         opts = new Options();
     }
     if (opts.Path == null)
     {
         opts.Path = "/socket.io";
     }
     this.Opts = opts;
     this.Nsps = new System.Collections.Concurrent.ConcurrentDictionary<string, Socket>();
     this.Subs = new Queue<On.IHandle>();
     this.Reconnection(opts.Reconnection);
     this.ReconnectionAttempts(opts.ReconnectionAttempts != 0 ? opts.ReconnectionAttempts : int.MaxValue);
     this.ReconnectionDelay(opts.ReconnectionDelay != 0 ? opts.ReconnectionDelay : 1000);
     this.ReconnectionDelayMax(opts.ReconnectionDelayMax != 0 ? opts.ReconnectionDelayMax : 5000);
     this.Timeout(opts.Timeout < 0 ? 20000 : opts.Timeout);
     this.ReadyState = ReadyStateEnum.CLOSED;
     this.Uri = uri;
     this.Connected = 0;
     this.Attempts = 0;
     this.Encoding = false;
     this.PacketBuffer = new List<Parser.Packet>();
     this.Encoder = new Parser.Parser.Encoder();
     this.Decoder = new Parser.Parser.Decoder();
     this.AutoConnect = opts.AutoConnect;
     if (AutoConnect)
     {
         Open();
     }
 }
Example #42
0
 private Manager()
 {
     _runningProcesses = new System.Collections.Concurrent.ConcurrentDictionary<int, Task>();
 }
Example #43
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");
                }
            }
        }
Example #44
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");
                }
            }
        }
Example #45
0
File: Client.cs Project: vebin/BD2
 public Client(BD2.Daemon.TransparentAgent agent, BD2.Chunk.ChunkRepository repo, string databaseName)
 {
     if (agent == null)
         throw new ArgumentNullException ("agent");
     if (repo == null)
         throw new ArgumentNullException ("repo");
     if (databaseName == null)
         throw new ArgumentNullException ("databaseName");
     this.agent = agent;
     this.repo = repo;
     this.databaseName = databaseName;
     typeIDs = new Dictionary<Type, long> ();
     typeIDs.Add (typeof(bool), 1);
     typeIDs.Add (typeof(char), 2);
     typeIDs.Add (typeof(byte), 3);
     typeIDs.Add (typeof(byte[]), 4);
     typeIDs.Add (typeof(short), 5);
     typeIDs.Add (typeof(int), 6);
     typeIDs.Add (typeof(long), 7);
     typeIDs.Add (typeof(float), 8);
     typeIDs.Add (typeof(double), 9);
     typeIDs.Add (typeof(Guid), 10);
     typeIDs.Add (typeof(String), 11);
     typeIDs.Add (typeof(DateTime), 12);
     tableDataRequests = new SortedDictionary<Guid, Table> ();
     frontend = new BD2.Frontend.Table.Frontend (new BD2.Frontend.Table.GenericValueDeserializer ());
     frontends = new BD2.Core.FrontendBase[] { frontend };
     db = new BD2.Core.Database (new BD2.Chunk.ChunkRepository[] { repo }, frontends, new byte[]{ }, databaseName);
     ss = db.GetSnapshot ("Primary");
     frontendInstance = (BD2.Frontend.Table.FrontendInstance)frontend.GetInstanse (ss);
     tableColumns = new System.Collections.Concurrent.ConcurrentDictionary<Table, System.Collections.Concurrent.BlockingCollection<Column>> ();
     tables = new SortedDictionary<Guid, Tuple<Table, List<Column>>> ();
 }