/// <summary> /// 注册一个事件到指定的命令模型类型。 /// </summary> /// <param name="commandType">命令模型类型。</param> /// <param name="event">事件。</param> public virtual void Register(Type commandType, IEvent @event) { var key = this.GetKey(commandType); Events.AddOrUpdate(key, k => new List <IEvent> { @event }, (k, l) => { l.Add(@event); return(l); }); }
static int _m_AddOrUpdate(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 == 4 && (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)) && translator.Assignable <System.Func <long, ulong, ulong> >(L, 4)) { long _key = LuaAPI.lua_toint64(L, 2); ulong _addValue = LuaAPI.lua_touint64(L, 3); System.Func <long, ulong, ulong> _updateValueFactory = translator.GetDelegate <System.Func <long, ulong, ulong> >(L, 4); ulong gen_ret = gen_to_be_invoked.AddOrUpdate( _key, _addValue, _updateValueFactory); LuaAPI.lua_pushuint64(L, gen_ret); return(1); } if (gen_param_count == 4 && (LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 2) || LuaAPI.lua_isint64(L, 2)) && translator.Assignable <System.Func <long, ulong> >(L, 3) && translator.Assignable <System.Func <long, ulong, ulong> >(L, 4)) { long _key = LuaAPI.lua_toint64(L, 2); System.Func <long, ulong> _addValueFactory = translator.GetDelegate <System.Func <long, ulong> >(L, 3); System.Func <long, ulong, ulong> _updateValueFactory = translator.GetDelegate <System.Func <long, ulong, ulong> >(L, 4); ulong gen_ret = gen_to_be_invoked.AddOrUpdate( _key, _addValueFactory, _updateValueFactory); 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>.AddOrUpdate!")); }
private void SwitchToWindow(IntPtr windowHwnd, AutomationElement window) { if (windowHwnd.ToInt64() == 0) { throw new Exception("Window handle is 0."); } string elementKey = null; ElementCache parentCache = null; // find the window in cache if (_elementCache.Count > 0) { parentCache = Cache; Cache.TryGetElementKey(window, out elementKey); } var cache = _elementCache.AddOrUpdate(windowHwnd, _ => new ElementCache(elementKey, window, parentCache), (_, c) => c); cache.PrevWindowsHandle = _windowHwnd; _windowHwnd = cache.Handle; window.SetFocus(); }
public RemotelyInitializedTransactionHandler CreateAndRegisterRITransactionHandler( uint transactionId, byte opcode) { RemotelyInitializedTransactionHandler riTh = null; for (int i = 0; i < m_instructionSets.Count && riTh == null; i++) { var instructionSet = m_instructionSets[i]; instructionSet.TryCreateRemotelyInitializedTransactionHandler(opcode, transactionId, out riTh); } if (riTh == null) { m_node.TryCreateRemotelyInitializedTransactionHandler(opcode, transactionId, out riTh); } if (riTh == null) { throw new KeyNotFoundException("No instruction set supported opcode " + opcode); } // Register the RIT Handler m_riTransactions.AddOrUpdate(riTh.TransactionID, riTh, (key, existingValue) => { throw new InvalidOperationException("RITH TID already existed in concurrent dict!"); }); return(riTh); }
public Domain.Service.IJobIndexPointCalculator GetCalculator(Domain.Model.Calculations.CalculationId calculationId) { lock (providerLock) { if (calculators.Any(i => !i.Key.Equals(calculationId) && i.Value.State == CalculatorState.Running)) { throw new Exception("تنها اجرای یک محاسبه امکان پذیر است."); } return(calculators.AddOrUpdate(calculationId, id => (JobIndexPointCalculator)ServiceLocator.Current.GetInstance <IJobIndexPointCalculator>(), (id, old) => { if (old != null) { if (old.State == CalculatorState.Running) { return old; } else { ServiceLocator.Current.Release(old); } } return (JobIndexPointCalculator)ServiceLocator.Current.GetInstance <IJobIndexPointCalculator>(); })); } }
static CatService() { ThreadPool.QueueUserWorkItem((o) => { while (true) { try { if (requests.Count == 0) { requestHandler.WaitOne(); } var flight = string.Empty; if (!requests.TryDequeue(out flight)) { continue; } var result = new Cat(flight, FrmMain.MonitorProcess).Catch(); var match = Regex.Match(result, "flightNo\":\"(?<value>.*?)\""); if (match.Success) { var f = match.Groups["value"].Value.Trim(); results.AddOrUpdate(f, result, (x, y) => y); waitHandler.Set(); } } catch { } } }, null); }
public void AddDevice(string deviceId) { devices.AddOrUpdate(deviceId, deviceId, (key, existing) => { return(deviceId); }); }
public static void AddDiagnosticsLog(DiagnosticsLog log) { logs.AddOrUpdate(log.Name, log.TotalSeconds, (s, i) => { return(logs[s] + i); }); }
/* * private async void PbiView_DatasetChanged(object sender, EventArgs e) * { * var selectedDataset = PbiView.SelectedDataset; * if (selectedDataset == null) return; * Log.Information($"Dataset:{selectedDataset.Name}"); * * Dax.ViewModel.VpaModel newModel = null; * if (CacheVpaModels.TryGetValue(selectedDataset, out newModel)) * { * CurrentVpaModel = newModel; * return; * } * * // Loader and show VPAX * DisplayStatus($"Loading VertiPaq Analyzer from dataset {selectedDataset.Name} ..."); * await Task.Run(() => * { * newModel = GetVpaModel(selectedDataset.Name, selectedDataset.Id); * }); * if (newModel != null) * { * CacheVpaModels.AddOrUpdate(selectedDataset, newModel, (key, oldValue) => newModel); * CurrentVpaModel = newModel; * DisplayStatus(""); * } * else * { * DisplayStatus($"Error reading VertiPaq Analyzer from dataset {selectedDataset.Name}"); * } * } */ private async void PbiTreeView_DatasetChanged(object sender, EventArgs e) { var selectedDataset = PbiTreeView.SelectedDataset; if (selectedDataset == null) { return; } Log.Information($"Dataset:{selectedDataset.Name}"); Dax.ViewModel.VpaModel newModel = null; if (CacheVpaModels.TryGetValue(selectedDataset, out newModel)) { CurrentVpaModel = newModel; return; } // Loader and show VPAX DisplayStatus($"Loading VertiPaq Analyzer from dataset {selectedDataset.Name} ..."); await Task.Run(() => { newModel = GetVpaModel(selectedDataset.Name, selectedDataset.Id); }); if (newModel != null) { CacheVpaModels.AddOrUpdate(selectedDataset, newModel, (key, oldValue) => newModel); CurrentVpaModel = newModel; DisplayStatus(""); } else { DisplayStatus($"Error reading VertiPaq Analyzer from dataset {selectedDataset.Name}"); } }
/// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="name"></param> /// <param name="files"></param> /// <returns></returns> public HttpOperation SetParam(string key, string name, Stream files) { if (key.IsEmpty()) { return(this); } if (files == null || !files.CanRead || files.Length <= 0) { FileUpload t; filedict.TryRemove(key, out t); t?.Dispose(); return(this); } var fu = new FileUpload() { fs = files, key = key, name = name }; filedict.AddOrUpdate(key, fu, (k, v) => { if (files != v?.fs) { v?.Dispose(); } return(fu); }); return(this); }
private void CheckAssertion(string solverName, string solverCallArg, int i) { string args = Options.outputPath + @"/" + Options.splitFilesDir + @"/intermediate_" + i.ToString() + ".bpl " + solverCallArg + @" /timeLimit:10 /errorLimit:1"; bool boogie_result = ExecuteBoogieBinary(args); shared_result_struct.AddOrUpdate(i, boogie_result, (x, y) => boogie_result); }
public void SetRealValue(double x, double y, double value) { if (Math.Abs(value) > 0.000000001) { _RealCity.AddOrUpdate(Mars.Interfaces.Environment.Position.CreatePosition(x, y), value, (position, s) => value); } }
//private int _cacheCounter = 0; private CacheEntry GetCache(DirectoryEntry e) { CacheEntry ce; if (!_cache.TryGetValue(e.Offset, out ce)) { ce = new CacheEntry() { File = e.Filename }; byte[] data; lock (_data) { switch (e.Flags & FileFlags.COMPRESSION_FLAGS) { case FileFlags.CompressLZS: data = new byte[e.Length]; _data.Position = e.Offset; _data.Read(data, 0, e.Length); var ms = new System.IO.MemoryStream(data); var output = new System.IO.MemoryStream(); Lzs.Decode(ms, output); data = new byte[output.Length]; output.Position = 0; output.Read(data, 0, data.Length); ce.Data = data; break; case FileFlags.CompressLZMA: _data.Position = e.Offset; int decSize = _data.ReadInt(), propSize = _data.ReadInt(); byte[] props = new byte[propSize]; _data.Read(props, 0, props.Length); byte[] cdata = new byte[e.Length - propSize - 8]; _data.Read(cdata, 0, cdata.Length); data = new byte[decSize]; /* var lzma = new SharpCompress.Compressor.LZMA.LzmaStream(props, new System.IO.MemoryStream(cdata)); lzma.Read(data, 0, data.Length); */ int srcSize = cdata.Length; switch (LzmaUncompress(data, ref decSize, cdata, ref srcSize, props, props.Length)) { case SZ_OK: //Woohoo! break; default: throw new IrosArcException("Error decompressing " + e.Filename); } ce.Data = data; break; default: throw new IrosArcException("Bad compression flags " + e.Flags.ToString()); } } _cache.AddOrUpdate(e.Offset, ce, (_, __) => ce); } ce.LastAccess = DateTime.Now; CleanCache(); /* if ((_cacheCounter++ % 100) == 0) System.Diagnostics.Debug.WriteLine("IRO cache contents; " + String.Join(",", _cache.Values.Select(e => e.File))); */ return ce; }
public void SetPanelText(long id, string text) { _tasks.AddOrUpdate(id, l => new ProcessingTask { Description = text }, (l, t) => new ProcessingTask { Description = text }); Notify(t => t.Tasks); }
public IUser GetUser(string userid) { if (!_dict.TryGetValue(userid, out IUser user)) { user = new UserTest(userid); _dict.AddOrUpdate(userid, user, (_, u) => u); } return(user); }
public void AddDynamic(ITemplateKey key, ITemplateSource source) { _dynamicTemplates.AddOrUpdate(key, source, (k, oldSource) => { if (oldSource.Template != source.Template) { throw new InvalidOperationException("The same key was already used for another template!"); } return(source); }); }
protected virtual void ParseProgramStreamMap(Container.Node node) { if (node.Identifier[3] != Mpeg.StreamTypes.ProgramStreamMap) { return; } int dataLength = node.Data.Length; if (dataLength < 4) { return; } byte mapId = node.Data[0]; byte reserved = node.Data[1]; ushort infoLength = Common.Binary.ReadU16(node.Data, 2, Common.Binary.IsLittleEndian); ushort mapLength = Common.Binary.ReadU16(node.Data, 4 + infoLength, Common.Binary.IsLittleEndian); int offset = 4 + infoLength + 2; int crcOffset = dataLength - 4; //While data remains in the map while (offset < crcOffset) { //Find out the type of item it is byte esType = node.Data[offset++]; //Find out the elementary stream id byte esId = node.Data[offset++]; //find out how long the info is ushort esInfoLength = Common.Binary.ReadU16(node.Data, offset, Common.Binary.IsLittleEndian); //Get a array containing the info Common.MemorySegment esData = esInfoLength == 0 ? Media.Common.MemorySegment.Empty : new Common.MemorySegment(node.Data, offset, esInfoLength); //node.Data.Skip(offset).Take(esInfoLength).ToArray(); //Create the entry var entry = new Tuple <byte, Common.MemorySegment>(esType, esData); //should keep entries until crc is updated if present and then insert. //Add it to the ProgramStreams m_ProgramStreams.AddOrUpdate(esId, entry, (id, old) => entry); //Move the offset offset += 2 + esInfoLength; } //Map crc }
public Address(string city, string street, string houseNumber, string apartment, string province, string cityType = null) { if (string.IsNullOrEmpty(cityType)) { if (string.IsNullOrWhiteSpace(city) == false) { string[] parts = city.Split('.'); if (parts.Length == 2) { this.CityType = parts[0] + "."; this.City = parts[1]; } else if (parts.Length == 1) { this.CityType = parts[0].StartsWith("Дач") ? "дачи" : "?"; this.City = parts[0]; } else { this.CityType = string.Empty; this.City = city; } } else { this.City = this.CityType = string.Empty; } } else { this.City = city; this.CityType = cityType; } this.Street = string.IsNullOrWhiteSpace(street) ? string.Empty : street; this.HouseNumber = string.IsNullOrWhiteSpace(houseNumber) ? string.Empty : houseNumber; this.Apartment = string.IsNullOrWhiteSpace(apartment) ? string.Empty : apartment; this.Province = string.IsNullOrWhiteSpace(province) ? string.Empty : province; string s = this.CityAndStreetWithHouse; if (DictionaryStreetWithHouseNumber.ContainsKey(s) == false) { DictionaryStreetWithHouseNumber.AddOrUpdate(s, 1u, (string key, uint value) => { return(value); }); } else { DictionaryStreetWithHouseNumber[s] = DictionaryStreetWithHouseNumber[s] + 1; } }
static void Main(string[] args) { var cd = new System.Collections.Concurrent.ConcurrentDictionary <int, int>(); var a = 0; var b = 1; var c = 2; cd[1] = a; Task.WaitAll( Task.Factory.StartNew(() => cd.AddOrUpdate(1, b, (key, existingValue) => { Console.WriteLine("b"); if (existingValue < b) { Console.WriteLine("b update"); System.Threading.Thread.Sleep(2000); return(b); } else { Console.WriteLine("b no change"); return(existingValue); } })), Task.Factory.StartNew(() => cd.AddOrUpdate(1, c, (key, existingValue) => { Console.WriteLine("c start"); if (existingValue < c) { Console.WriteLine("c update"); return(c); } else { Console.WriteLine("c no change"); return(existingValue); } }))); Console.WriteLine("Value: {0}", cd[1]); var input = Console.ReadLine(); }
public bool AddSessionModel(SessionVM session) { var sessionInDict = _sessionCache.AddOrUpdate(session.SessionToken, session ,(key, s) => { s.NextLoginTimeout = session.NextLoginTimeout; s.LastActivityTime = session.LastActivityTime; return s; }); return sessionInDict != null; }
public static void AddResponse(string result) { var match = Regex.Match(result, "flightNo\":\"(?<value>.*?)\""); if (match.Success) { var flight = match.Groups["value"].Value.Trim(); results.AddOrUpdate(flight, result, (x, y) => y); waitHandler.Set(); } }
/// <summary> /// Full constructor. /// </summary> /// <param name="allowedAuthorities">An enumerable of media types that are allowed by this condition.</param> public WebRequestContentMediaTypeCondition(IEnumerable <string> allowedAuthorities) : this() { if (allowedAuthorities == null) { return; } foreach (var item in allowedAuthorities) { _AllowedMediaTypes.AddOrUpdate(item, item, (key, oldValue) => item); } }
/// <summary> /// Saves the specified HTTP <paramref name="response" /> to the message store as an asynchronous operation. /// </summary> /// <param name="request">The HTTP request message that was sent.</param> /// <param name="response">The HTTP response messsage to save.</param> /// <returns> /// The task object representing the asynchronous operation. /// </returns> public override async Task SaveAsync(HttpRequestMessage request, HttpResponseMessage response) { // don't save content if not success if (!response.IsSuccessStatusCode || response.Content == null || response.StatusCode == HttpStatusCode.NoContent) { return; } var httpContent = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var fakeResponse = Convert(response); var key = GenerateKey(request); var container = new FakeResponseContainer { HttpContent = httpContent, ResponseMessage = fakeResponse }; // save to store _responseStore.AddOrUpdate(key, container, (k, o) => container); }
private void SwitchToWindow(IntPtr windowHwnd, AutomationElement window) { if (windowHwnd.ToInt64() == 0) { throw new Exception("Window handle is 0."); } var cache = _elementCache.AddOrUpdate(windowHwnd, hwnd => new ElementCache(window), (e, c) => c); cache.PrevWindowsHandle = _windowHwnd; _windowHwnd = cache.Handle; window.SetFocus(); }
/// <summary> /// Executes the specified actions and returns the results of the executions. /// </summary> /// <param name="parameters">Parameters.</param> /// <param name="eventType">Event type.</param> /// <returns></returns> private async Task ExecuteActionsAsync(SaveParameters parameters, ETableDbEventType eventType) { var execution = await this.GetTableExecutionSources(parameters, eventType) .Select(e => new ExecutionSource() { ExecutionType = e.ExecutionType, ExecutionText = e.ExecutionText, TableConfiguration = new TableConfiguration() { ConnectionString = e.TableConfiguration.ConnectionString } }) .ToListAsync(); System.Collections.Concurrent.ConcurrentDictionary <string, object> resultDictionary = new System.Collections.Concurrent.ConcurrentDictionary <string, object>(); int index; for (index = 0; index < execution.Count; index++) { var factory = base.Context.QueryBuilderOptions.ConnectionsPool[execution[index].TableConfiguration.ConnectionString]; var q = new ParserFull(factory) .ParseToQuery(execution[index].ExecutionText, resultDictionary); var result = (await q.GetAsync()).Cast <IDictionary <string, object> >().ToList(); Parallel.For(0, result.Count, (i) => { Parallel.ForEach(result[i], (e) => { resultDictionary.AddOrUpdate(e.Key, e.Value, (f, g) => g); }); }); } foreach (string key in resultDictionary.Keys) { if (!parameters.AdditionalParameters.ContainsKey(key)) { parameters.AdditionalParameters.Add(key, resultDictionary[key]); } else { parameters.AdditionalParameters[key] = resultDictionary[key]; } } }
/// <summary> /// 获取指定键的原子递增序列。 /// </summary> /// <param name="key">序列的键。</param> /// <param name="increment">递增量。</param> /// <returns>返回递增的序列。</returns> public virtual long Increment(string key, long increment = 1) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } var redisProvider = this.Container.GetFixedService <IRedisProvider>(); if (redisProvider != null) { var client = redisProvider.GetRedisClient(); return(client.HIncrBy(ReidsHashKey, key, increment)); } return(_dict.AddOrUpdate(key, increment, (k, v) => v += increment)); }
private WorkbookState WorkbookOpenHelper(Excel.Workbook workbook) { WorkbookState wbs; if (!wbstates.ContainsKey(workbook)) { wbs = new WorkbookState(Globals.ThisAddIn.Application, workbook); wbstates.Add(workbook, wbs); wbShutdown.AddOrUpdate(workbook, false, (k, v) => v); } else { wbs = wbstates[workbook]; } return(wbs); }
public Entities.VehicleBaseInfo LoadAllVehicleInfo(string vinno) { Entities.VehicleBaseInfo vehicleBaseInfo; // 先从缓存中读取 if (!_vehicleBaseInfoDic.TryGetValue(vinno, out vehicleBaseInfo)) { // 读取不到从数据库里读取 vehicleBaseInfo = _dbProvider.LoadAllVehicleInfo(vinno); if (vehicleBaseInfo != null) { // 读取到数据则更新缓存 _vehicleBaseInfoDic.AddOrUpdate(vinno, vehicleBaseInfo, (i, v) => vehicleBaseInfo); } } return(vehicleBaseInfo); }
public static void Configure(params TypeDefinition[] typeDefinitions) { if (typeDefinitions == null) { return; } foreach (var typeDefinition in typeDefinitions) { InstanceCache.AddOrUpdate(typeDefinition.Type, key => { return(new TypeDescriptor(typeDefinition)); }, (key, oldValue) => { return(new TypeDescriptor(typeDefinition)); }); } }
public RawProxyAttribute(Type type, string guid, string deserializeMethodName) { if (guid == null) { throw new ArgumentNullException("guid"); } if (deserializeMethodName == null) { throw new ArgumentNullException("deserializeMethodName"); } this.deserializeMethodName = deserializeMethodName; this.guid = Guid.Parse(guid); deserializeMethod = type.GetMethod(deserializeMethodName, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); attribs.AddOrUpdate(this.guid, (g) => { return(this); }, (g, o) => { return(this); } ); }