public RepositoryCache() { cacheMap = new Dictionary<Key, WeakReference<Repository>>(); openLocks = new Lock[4]; for (int i = 0; i < openLocks.Length; i++) openLocks[i] = new Lock(); }
public bool Lock(RedisKey resource, TimeSpan ttl, out Lock lockObject) { var task = LockAsync(resource, ttl); task.Wait(); var result = task.Result; lockObject = result.Item2; return result.Item1; }
public void Release(Lock @lock) { lock (this) { locks.Remove(@lock); Lockable.Released(@lock); Monitor.PulseAll(this); } }
public CompositionLock(bool isThreadSafe) { this._isThreadSafe = isThreadSafe; if (isThreadSafe) { this._stateLock = new Lock(); } }
public Lock NewLock(LockingMode mode, AccessType accessType) { lock (this) { var @lock = new Lock(this, mode, accessType); Acquire(@lock); @lock.OnAcquired(); return @lock; } }
/// <summary> /// Try to aquire a machine-wide lock named 'name'. Returns null in case of failure (it doesn't wait at all). /// </summary> /// <param name="name"></param> /// <returns></returns> public static Lock Create (string name) { Lock result = new Lock (); Mutex mutex; Semaphore semaphore; switch (Configuration.LockingAlgorithm.ToLowerInvariant ()) { case "mutex": mutex = new Mutex (true, name); if (mutex.WaitOne (1 /* ms */)) { result.mutex = mutex; return result; } return null; case "file": try { result.file = File.Open (Path.Combine (Path.GetTempPath (), name + ".lock"), FileMode.Create, FileAccess.ReadWrite, FileShare.Read); return result; } catch (IOException ex) { Logger.Log ("Could not aquire builder lock: {0}", ex.Message); return null; } case "fileexistence": case "fileexistance": string tmp = Path.Combine (Path.GetTempPath (), name + ".fileexistence-lock--delete-to-unlock"); Logger.Log ("Checking file existence for {0}", tmp); if (File.Exists (tmp)) { try { if (ProcessHelper.Exists (int.Parse (File.ReadAllText (tmp)))) { Logger.Log ("File lock corresponds to an existing process."); return null; } } catch (Exception ex) { Logger.Log ("Could not confirm that file lock corresponds to a non-existing process: {0}", ex.Message); return null; } Logger.Log ("File lock corresponds to a dead process, lock acquired"); } // there is a race condition here. // given that the default setup is to execute a program at most once per minute, // the race condition is harmless. File.WriteAllText (tmp, Process.GetCurrentProcess ().Id.ToString ()); result.file_existence = tmp; return result; case "semaphore": semaphore = new Semaphore (1, 1, name); if (semaphore.WaitOne (1 /* ms */)) { result.semaphore = semaphore; return result; } return null; default: Logger.Log ("Unknown locking algorithm: {0} (using default 'semaphore')", Configuration.LockingAlgorithm); goto case "semaphore"; } }
public SEMA4(Machine machine) { sysbus = machine.SystemBus; irqLock = new object(); locks = new Lock[NumberOfEntries]; for(var i = 0; i < locks.Length; i++) { locks[i] = new Lock(this, i); } CPU0 = new GPIO(); CPU1 = new GPIO(); }
private static MCS.Library.SOA.DataObjects.Lock GetInstanceOfLock(string lockId, IUser user) { Lock _lock = new Lock(); _lock.LockID = lockId; _lock.LockTime = DateTime.Now; _lock.LockType = LockType.ActivityLock; double db = 0.0; _lock.EffectiveTime = TimeSpan.FromMinutes(db); _lock.PersonID = user.ID; return _lock; }
public bool GetLock(DataLocation dataLocation) { lock (_locks) { if (_locks.Any(takenLock => takenLock.Overlap(dataLocation))) { return false; } Lock newLock = new Lock(dataLocation); _locks.Add(newLock); } return true; }
public bool Lock(RedisKey resource, TimeSpan ttl, out Lock lockObject) { var val = CreateUniqueLockId(); Lock innerLock = null; bool successfull = retry(DefaultRetryCount, DefaultRetryDelay, () => { try { int n = 0; var startTime = DateTime.Now; // Use keys for_each_redis_registered( redis => { if (LockInstance(redis, resource, val, ttl)) n += 1; } ); /* * Add 2 milliseconds to the drift to account for Redis expires * precision, which is 1 milliescond, plus 1 millisecond min drift * for small TTLs. */ var drift = Convert.ToInt32((ttl.TotalMilliseconds * ClockDriveFactor) + 2); var validity_time = ttl - (DateTime.Now - startTime) - new TimeSpan(0, 0, 0, 0, drift); if (n >= Quorum && validity_time.TotalMilliseconds > 0) { innerLock = new Lock(resource, val, validity_time); return true; } else { for_each_redis_registered( redis => { UnlockInstance(redis, resource, val); } ); return false; } } catch (Exception) { return false; } }); lockObject = innerLock; return successfull; }
public DisposableWrapperCatalog(ComposablePartCatalog innerCatalog, bool isThreadSafe) { if (innerCatalog == null) throw new ArgumentNullException(nameof(innerCatalog)); _lock = new Lock(isThreadSafe, LockRecursionPolicy.NoRecursion); _cache = new Dictionary<ComposablePartDefinition, ComposablePartDefinition>(); _innerCatalog = innerCatalog; _compositionOrigin = innerCatalog as ICompositionElement; var notify = innerCatalog as INotifyComposablePartCatalogChanged; if (notify == null) return; notify.Changed += OnChanged; notify.Changing += OnChanging; }
internal void CheckAccess(Lock @lock) { lock (this) { // Error checking. The queue must contain the Lock. if (!locks.Contains(@lock)) throw new InvalidOperationException("Queue does not contain the given Lock"); // If 'READ' bool blocked; int index; if (@lock.AccessType == AccessType.Read) { do { blocked = false; index = locks.IndexOf(@lock); int i; for (i = index - 1; i >= 0 && !blocked; --i) { var testLock = locks[i]; if (testLock.AccessType == AccessType.Write) blocked = true; } if (blocked) { Monitor.Wait(this); } } while (blocked); } else { do { blocked = false; index = locks.IndexOf(@lock); if (index != 0) { blocked = true; Monitor.Wait(this); } } while (blocked); } // Notify the Lock table that we've got a lock on it. // TODO: Lock.Table.LockAcquired(Lock); } }
public override void Process() { DCTSimpleProperty property = DataProperty as DCTSimpleProperty; if (null != property) { var containerElement = document.MainDocumentPart.Document.Body .Descendants<SdtElement>().Where(o => o.SdtProperties.Descendants<SdtAlias>().Any(a => a.Val == DataProperty.TagID)).FirstOrDefault(); if (null == containerElement) return; var runElement = containerElement.Descendants<Run>().First(); runElement.RemoveAllChildren(); runElement.AppendChild<Text>(new Text(GeneralFormatter.ToString(property.Value, property.FormatString))); if (property.IsReadOnly) { Lock lockControl = new Lock(); lockControl.Val = LockingValues.SdtContentLocked; containerElement.SdtProperties.Append(lockControl); } } }
void case_1008() #line 6738 "cs-parser.jay" { if (yyVals[0+yyTop] is EmptyStatement && lexer.peek_token () == Token.OPEN_BRACE) Warning_EmptyStatement (GetLocation (yyVals[0+yyTop])); yyVal = new Lock ((Expression) yyVals[-2+yyTop], (Statement) yyVals[0+yyTop], GetLocation (yyVals[-4+yyTop])); lbag.AddStatement (yyVal, GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[-1+yyTop])); }
public virtual Statement VisitLock(Lock Lock){ if (Lock == null) return null; Lock.Guard = this.VisitExpression(Lock.Guard); Lock.Body = this.VisitBlock(Lock.Body); return Lock; }
public PChangeStatLockStateRequest(byte stat, Lock state) : base(0xBF) { WriteUShort(0x1A); WriteByte(stat); WriteByte((byte)state); }
internal UpgradableReadLock(Lock @lock) { _isDisposed = 0; _lock = @lock; _lock.EnterUpgradableReadLock(); }
/// <summary> /// Loads the most updated configuration creating any resources as needed. /// </summary> /// <param name="bucketConfig">The latest <see cref="IBucketConfig"/> /// that will drive the recreation if the configuration context.</param> /// <param name="force">True to force the reconfiguration.</param> public override void LoadConfig(IBucketConfig bucketConfig, bool force = false) { try { Lock.EnterWriteLock(); var nodes = bucketConfig.GetNodes(); if (BucketConfig == null || !nodes.AreEqual(_bucketConfig.GetNodes()) || !Servers.Any() || force) { var clientBucketConfig = ClientConfig.BucketConfigs[bucketConfig.Name]; var servers = new Dictionary <IPAddress, IServer>(); foreach (var adapter in nodes) { var endpoint = adapter.GetIPEndPoint(clientBucketConfig.UseSsl); try { Log.Info( m => m("o1-Creating the Servers {0} list using rev#{1}", Servers.Count(), bucketConfig.Rev)); IServer server; if (adapter.IsDataNode) //a data node so create a connection pool { var poolConfiguration = ClientConfig.BucketConfigs[bucketConfig.Name].PoolConfiguration; var connectionPool = ConnectionPoolFactory(poolConfiguration, endpoint); var ioStrategy = IOStrategyFactory(connectionPool); server = new Core.Server(ioStrategy, adapter, ClientConfig, bucketConfig, Transcoder, QueryCache) { SaslFactory = SaslFactory }; server.CreateSaslMechanismIfNotExists(); SupportsEnhancedDurability = ioStrategy.SupportsEnhancedDurability; } else { server = new Core.Server(null, adapter, ClientConfig, bucketConfig, Transcoder, QueryCache); } servers.Add(endpoint.Address, server); } catch (Exception e) { Log.ErrorFormat("Could not add server {0}. Exception: {1}", endpoint, e); } } UpdateServices(servers); var old = Interlocked.Exchange(ref Servers, servers); Log.Info(m => m("Creating the KeyMapper list using rev#{0}", bucketConfig.Rev)); var vBucketKeyMapper = new VBucketKeyMapper(Servers, bucketConfig.VBucketServerMap, bucketConfig.Rev); Interlocked.Exchange(ref KeyMapper, vBucketKeyMapper); Interlocked.Exchange(ref _bucketConfig, bucketConfig); if (old != null) { foreach (var server in old.Values) { server.Dispose(); } old.Clear(); } } else { if (BucketConfig == null || !BucketConfig.IsVBucketServerMapEqual(bucketConfig) || force) { Log.Info(m => m("Creating the KeyMapper list using rev#{0}", bucketConfig.Rev)); var vBucketKeyMapper = new VBucketKeyMapper(Servers, bucketConfig.VBucketServerMap, bucketConfig.Rev); Interlocked.Exchange(ref KeyMapper, vBucketKeyMapper); Interlocked.Exchange(ref _bucketConfig, bucketConfig); } } } catch (Exception e) { Log.Error(e); } finally { Lock.ExitWriteLock(); } }
public void Update() { /* * // Debug shows mining area * var position = m_block.PositionComp.GetPosition(); * var direction = Vector3D.Normalize(-m_block.PositionComp.WorldMatrix.Up); * var color = Color.Red; * for (int r = 0; r < NaniteConstructionManager.Settings.MiningDepth; r++) * { * MatrixD matrix = MatrixD.CreateTranslation(position + (direction * NaniteConstructionManager.Settings.MiningRadius * r)); * MySimpleObjectDraw.DrawTransparentSphere(ref matrix, NaniteConstructionManager.Settings.MiningRadius, ref color, MySimpleObjectRasterizer.Solid, 20); * } */ m_updateCount++; if (!m_initialize) { m_initialize = true; Initialize(); if (!CheckWorking()) { return; } } if (Sync.IsClient) { foreach (var item in m_effects) { if (IsWorking) { item.ActiveUpdate(); } else { item.InactiveUpdate(); } } } if (Sync.IsServer) { if (DateTime.Now - m_syncLastUpdate > TimeSpan.FromSeconds(3)) { m_syncLastUpdate = DateTime.Now; SendDetails(); } } if (m_updateCount % 240 == 0) { if (!CheckWorking()) { m_working = false; return; } m_working = true; } if (!m_working) { using (Lock.AcquireExclusiveUsing()) m_oreList = null; //using(LocationLock.AcquireExclusiveUsing()) // m_oreLocations.Clear(); return; } if (DateTime.Now - m_lastUpdate > TimeSpan.FromSeconds(30) && !m_busy) { m_lastUpdate = DateTime.Now; m_working = true; m_busy = true; //m_block.SetEmissiveParts("Emissive-Beacon", Color.FromNonPremultiplied(new Vector4(0.3f, 0.15f, 0.0f, 1f)), 1f); //MyCubeBlockEmissive.SetEmissiveParts((MyEntity)m_block, 1.0f, Color.FromNonPremultiplied(new Vector4(0.3f, 0.15f, 0.0f, 1f)), Color.White); if (Sync.IsServer) { MyAPIGateway.Parallel.Start(ScanVoxelWork, ScanVoxelComplete); } } //((IMyFunctionalBlock)m_block).RefreshCustomInfo(); }
public void Unlock(bool isOpen, Lock theLock, Key theKey) { TheKnob.Blocked = !isOpen; }
protected virtual void ExclusiveProcessing(bool processActions) { NullSafeSequencer.PointArg(SeqPointTypeUC.Match, TickGeneratorSequencer.ExclusiveProcessing, processActions); TickGeneratorStatus lastStatus; using (Lock.Enter()) { ActiveProcessing = true; NullSafeSequencer.PointArg(SeqPointTypeUC.Match, TickGeneratorSequencer.BeginActiveProcessing, Status); } while (true) { using (Lock.Enter()) { lastStatus = Status; while (Requests.Count > 0 && WorkingRequests.Count < MaxActiveRequests) { WorkingRequests.Enqueue(Requests.Dequeue()); } if (Requests.Count <= 0 && WorkingRequests.Count <= 0) { break; } } CallBackRequest.Processing(lastStatus, WorkingRequests, Actions); } bool processing = processActions && lastStatus != TickGeneratorStatus.Disposed && Actions.Count > 0; NullSafeSequencer.PointArg(SeqPointTypeUC.Match, TickGeneratorSequencer.ActionsProcessing, processing); if (processing) { NullSafeSequencer.PointArg(SeqPointTypeUC.Notify, TickGeneratorSequencer.ActionsProcessingCount, Actions.Count); foreach (Action action in Actions) { action(); } } while (true) { using (Lock.Enter()) { lastStatus = Status; while (Requests.Count > 0 && WorkingRequests.Count < MaxActiveRequests) { WorkingRequests.Enqueue(Requests.Dequeue()); } if (Requests.Count <= 0 && WorkingRequests.Count <= 0) { break; } } CallBackRequest.Processing(lastStatus, WorkingRequests, Actions); } using (Lock.Enter()) { ActiveProcessing = false; CallBackRequest.Processing(lastStatus, Requests, Actions); if (Status == TickGeneratorStatus.Operating) { bool activate = false; activate |= Actions.Count > 0; activate |= Requests.Count > 0; TryUpdateTimer(activate); } else { TryUpdateTimer(activate: false); Period = null; Actions.Clear(); Status = TickGeneratorStatus.Disposed; DisposedTCS.TrySetResult(null); } NullSafeSequencer.PointArg(SeqPointTypeUC.Match, TickGeneratorSequencer.EndActiveProcessing, Status); } }
private void Start() { locker = GetComponentInParent <Lock>(); }
internal ReadLock(Lock @lock) { _isDisposed = 0; _lock = @lock; _lock.EnterReadLock(); }
//// Suffix for internal face names to indicate that the font data comes from the platform //// and not from the users font resolver. //public const string PlatformTag = "platform:"; /// <summary> /// Converts specified information about a required typeface into a specific font. /// </summary> /// <param name="familyName">Name of the font family.</param> /// <param name="fontResolvingOptions">The font resolving options.</param> /// <param name="typefaceKey">Typeface key if already known by caller, null otherwise.</param> /// <returns> /// Information about the typeface, or null if no typeface can be found. /// </returns> public static FontResolverInfo ResolveTypeface(string familyName, FontResolvingOptions fontResolvingOptions, string typefaceKey) { if (string.IsNullOrEmpty(typefaceKey)) { typefaceKey = XGlyphTypeface.ComputeKey(familyName, fontResolvingOptions); } try { Lock.EnterFontFactory(); // Was this typeface requested before? FontResolverInfo fontResolverInfo; if (FontResolverInfosByName.TryGetValue(typefaceKey, out fontResolverInfo)) { return(fontResolverInfo); } // Case: This typeface was not resolved before. // Is there a custom font resolver available? IFontResolver customFontResolver = GlobalFontSettings.FontResolver; if (customFontResolver != null) { // Case: Use custom font resolver. fontResolverInfo = customFontResolver.ResolveTypeface(familyName, fontResolvingOptions.IsBold, fontResolvingOptions.IsItalic); // If resolved by custom font resolver register info and font source. if (fontResolverInfo != null && !(fontResolverInfo is PlatformFontResolverInfo)) { string resolverInfoKey = fontResolverInfo.Key; FontResolverInfo existingFontResolverInfo; if (FontResolverInfosByName.TryGetValue(resolverInfoKey, out existingFontResolverInfo)) { // Case: A new typeface was resolved with the same info as a previous one. // Discard new object an reuse previous one. fontResolverInfo = existingFontResolverInfo; // Associate with typeface key. FontResolverInfosByName.Add(typefaceKey, fontResolverInfo); #if DEBUG // The font source should exist. Debug.Assert(FontSourcesByName.ContainsKey(fontResolverInfo.FaceName)); #endif } else { // Case: No such font resolver info exists. // Add to both dictionaries. FontResolverInfosByName.Add(typefaceKey, fontResolverInfo); Debug.Assert(resolverInfoKey == fontResolverInfo.Key); FontResolverInfosByName.Add(resolverInfoKey, fontResolverInfo); // Create font source if not yet exists. XFontSource previousFontSource; if (FontSourcesByName.TryGetValue(fontResolverInfo.FaceName, out previousFontSource)) { // Case: The font source exists, because a previous font resolver info comes // with the same face name, but was different in style simulation flags. // Nothing to do. } else { // Case: Get font from custom font resolver and create font source. byte[] bytes = customFontResolver.GetFont(fontResolverInfo.FaceName); XFontSource fontSource = XFontSource.GetOrCreateFrom(bytes); // Add font source's font resolver name if it is different to the face name. if (string.Compare(fontResolverInfo.FaceName, fontSource.FontName, StringComparison.OrdinalIgnoreCase) != 0) { FontSourcesByName.Add(fontResolverInfo.FaceName, fontSource); } } } } } else { // Case: There was no custom font resolver set. // Use platform font resolver. // If it was successful resolver info and font source are cached // automatically by PlatformFontResolver.ResolveTypeface. fontResolverInfo = PlatformFontResolver.ResolveTypeface(familyName, fontResolvingOptions, typefaceKey); } // Return value is null if the typeface could not be resolved. // In this case PDFsharp stops. return(fontResolverInfo); } finally { Lock.ExitFontFactory(); } }
protected override void OnLockError(Lock @lock, ErrorCodes error) { SendError(error); base.OnLockError(@lock, error); }
public static bool ExecuteScheduler(bool forcefullupdate) { DateTime start; Lock scheduler_lock = null; List <DBLane> lanes; List <DBHost> hosts; List <DBHostLane> hostlanes; List <XmlDocument> reports; try { scheduler_lock = Lock.Create("MonkeyWrench.Scheduler"); if (scheduler_lock == null) { log.Info("Could not aquire scheduler lock."); return(false); } log.Info("Scheduler lock aquired successfully."); is_executing = true; start = DateTime.Now; // SVNUpdater.StartDiffThread (); // Check reports reports = GetReports(forcefullupdate); using (DB db = new DB(true)) { lanes = db.GetAllLanes(); hosts = db.GetHosts(); hostlanes = db.GetAllHostLanes(); log.InfoFormat("Updater will now update {0} lanes.", lanes.Count); GITUpdater git_updater = null; // SVNUpdater svn_updater = null; foreach (DBLane lane in lanes) { if (!lane.enabled) { log.InfoFormat("Schedule: lane {0} is disabled, skipping it.", lane.lane); continue; } SchedulerBase updater; switch (lane.source_control) { /* * case "svn": * if (svn_updater == null) * svn_updater = new SVNUpdater (forcefullupdate); * updater = svn_updater; * break; * */ case "git": if (git_updater == null) { git_updater = new GITUpdater(forcefullupdate); } updater = git_updater; break; default: log.ErrorFormat("Unknown source control: {0} for lane {1}", lane.source_control, lane.lane); continue; } updater.Clear(); updater.AddChangeSets(reports); updater.UpdateRevisionsInDB(db, lane, hosts, hostlanes); } AddRevisionWork(db, lanes, hostlanes); AddWork(db, hosts, lanes, hostlanes); CheckDependencies(db, hosts, lanes, hostlanes); } // SVNUpdater.StopDiffThread (); log.InfoFormat("Update finished successfully in {0} seconds.", (DateTime.Now - start).TotalSeconds); return(true); } catch (Exception ex) { log.ErrorFormat("An exception occurred: {0}", ex); return(false); } finally { if (scheduler_lock != null) { scheduler_lock.Unlock(); } is_executing = false; } }
/// <summary> /// Constructs an executor that will grab the named lock. </summary> public With(Lock @lock, long lockWaitTimeout) { this.@lock = @lock; this.LockWaitTimeout = lockWaitTimeout; }
public SimLock(Lock kind, int id) { this.kind = kind; this.id = id; }
public override object Visit (Lock lockStatement) { var result = new LockStatement (); var location = LocationsBag.GetLocations (lockStatement); result.AddChild (new CSharpTokenNode (Convert (lockStatement.loc), LockStatement.LockKeywordRole), LockStatement.LockKeywordRole); if (location != null) result.AddChild (new CSharpTokenNode (Convert (location [0]), Roles.LPar), Roles.LPar); if (lockStatement.Expr != null) result.AddChild ((Expression)lockStatement.Expr.Accept (this), Roles.Expression); if (location != null && location.Count > 1) result.AddChild (new CSharpTokenNode (Convert (location [1]), Roles.RPar), Roles.RPar); if (lockStatement.Statement != null) result.AddChild ((Statement)lockStatement.Statement.Accept (this), Roles.EmbeddedStatement); return result; }
public void AddDirect(IEntityMetaData metaData, Object id, Object version, Object primitiveFilledObject, Object parentCacheValueOrArray, IObjRef[][] relations) { if (id == null) { throw new Exception("Key must be valid: " + primitiveFilledObject); } Type entityType = metaData.EntityType; sbyte idIndex = ObjRef.PRIMARY_KEY_INDEX; CacheKey[] oldAlternateCacheKeys = null; Object cacheValue; Lock writeLock = WriteLock; writeLock.Lock(); try { Object cacheValueR = GetCacheValueR(metaData, idIndex, id); cacheValue = GetCacheValueFromReference(cacheValueR); oldAlternateCacheKeys = (CacheKey[])keyToAlternateIdsMap.Get(entityType, idIndex, id); if (oldAlternateCacheKeys != null) { for (int a = oldAlternateCacheKeys.Length; a-- > 0;) { RemoveKeyFromCache(oldAlternateCacheKeys[a]); } } if (cacheValue != null) { if (cacheValue != primitiveFilledObject) { throw new Exception("There is already another instance of the same entity in this cache. This is a fatal state"); } // Object (same instance) already in cache. Nothing to do here } else { cacheValue = primitiveFilledObject; cacheValueR = CreateReference(cacheValue); this.keyToCacheValueDict.Put(entityType, idIndex, id, cacheValueR); } CacheKey[] newAlternateCacheKeys = oldAlternateCacheKeys; if (newAlternateCacheKeys == null) { // Allocate new array to hold alternate ids newAlternateCacheKeys = ExtractAlternateCacheKeys(metaData, parentCacheValueOrArray); } else { // reuse existing array for new alternate id-values ExtractAlternateCacheKeys(metaData, parentCacheValueOrArray, newAlternateCacheKeys); } if (newAlternateCacheKeys.Length > 0) { keyToAlternateIdsMap.Put(entityType, idIndex, id, newAlternateCacheKeys); PutAlternateCacheKeysToCache(metaData, newAlternateCacheKeys, cacheValueR); } } finally { writeLock.Unlock(); } if (WeakEntries) { AddHardRefTL(cacheValue); } AssignEntityToCache(primitiveFilledObject); if (relations != null && relations.Length > 0) { HandleValueHolderContainer((IValueHolderContainer)primitiveFilledObject, metaData.RelationMembers, relations); } if (primitiveFilledObject is IDataObject) { ((IDataObject)primitiveFilledObject).ToBeUpdated = false; } }
public CleanerService(SCMStore store) : base("CleanerService") { this.store = store; this.cleanerTaskLock = new ReentrantLock(); }
/// <exception cref="CouchbaseBootstrapException">Condition.</exception> public void LoadConfig(IOStrategy ioStrategy) { var supportsEnhancedDurability = false; try { Lock.EnterWriteLock(); Log.Info(m => m("o2-Creating the Servers list using rev#{0}", BucketConfig.Rev)); var clientBucketConfig = ClientConfig.BucketConfigs[BucketConfig.Name]; var servers = new Dictionary <IPAddress, IServer>(); var nodes = BucketConfig.GetNodes(); foreach (var adapter in nodes) { var endpoint = adapter.GetIPEndPoint(clientBucketConfig.UseSsl); try { IServer server = null; if (Equals(ioStrategy.EndPoint, endpoint) || nodes.Count() == 1) { server = new Core.Server(ioStrategy, adapter, ClientConfig, BucketConfig, Transcoder, QueryCache); supportsEnhancedDurability = ioStrategy.SupportsEnhancedDurability; SupportsEnhancedDurability = supportsEnhancedDurability; } else { if (adapter.IsDataNode) //a data node so create a connection pool { var poolConfiguration = ClientConfig.BucketConfigs[BucketConfig.Name].PoolConfiguration; var connectionPool = ConnectionPoolFactory(poolConfiguration, endpoint); var newIoStrategy = IOStrategyFactory(connectionPool); server = new Core.Server(newIoStrategy, adapter, ClientConfig, BucketConfig, Transcoder, QueryCache) { SaslFactory = SaslFactory }; server.CreateSaslMechanismIfNotExists(); //Note: "ioStrategy has" already made a HELO command to check if //the cluster supports enhanced durability so we are reusing the flag //instead of having "newIoStrategy" do it again, later. SupportsEnhancedDurability = ioStrategy.SupportsEnhancedDurability; } else { server = new Core.Server(null, adapter, ClientConfig, BucketConfig, Transcoder, QueryCache); } } servers.Add(endpoint.Address, server); } catch (Exception e) { Log.ErrorFormat("Could not add server {0}. Exception: {1}", endpoint, e); } } UpdateServices(servers); Log.Info(m => m("Creating the KeyMapper list using rev#{0}", BucketConfig.Rev)); var old = Interlocked.Exchange(ref Servers, servers); var vBucketKeyMapper = new VBucketKeyMapper(Servers, BucketConfig.VBucketServerMap, BucketConfig.Rev); Interlocked.Exchange(ref KeyMapper, vBucketKeyMapper); if (old != null) { foreach (var server in old.Values) { server.Dispose(); } old.Clear(); } } finally { Lock.ExitWriteLock(); } }
private void ScanVoxelWork() { try { if (m_oreList != null && DateTime.Now - m_lastRefresh < TimeSpan.FromMinutes(5)) { return; } m_lastRefresh = DateTime.Now; Vector3D position = m_block.GetPosition(); BoundingSphereD sphere = new BoundingSphereD(position, 2f); var entities = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere); if (!NaniteConstructionManager.HammerTerminalSettings.ContainsKey(m_block.EntityId)) { NaniteConstructionManager.HammerTerminalSettings.Add(m_block.EntityId, new NaniteHammerTerminalSettings(true)); } var allowedOreList = new HashSet <string>(NaniteConstructionManager.HammerTerminalSettings[m_block.EntityId].SelectedOres); DateTime start = DateTime.Now; Logging.Instance.WriteLine(string.Format("MINING Hammer Start Scan")); Dictionary <Vector3D, NaniteMiningItem> miningItems = new Dictionary <Vector3D, NaniteMiningItem>(100000); foreach (var item in entities) { var voxelMap = item as MyVoxelBase; if (voxelMap == null) { continue; } if (item.GetType().Name == "MyVoxelPhysics") { continue; } Logging.Instance.WriteLine(string.Format("Item: {0}:{1} - {2}", item.GetType().Name, item.EntityId, item.GetPosition())); //var direction = Vector3D.Normalize(item.GetPosition() - position); var direction = Vector3D.Normalize(-m_block.PositionComp.WorldMatrix.Up); for (int r = NaniteConstructionManager.Settings.MiningDepth - 1; r >= 0; r--) { DateTime readStart = DateTime.Now; ReadVoxel(voxelMap, position + (direction * NaniteConstructionManager.Settings.MiningRadius * r), miningItems, allowedOreList); //Logging.Instance.WriteLine(string.Format("Read Time: {0}", (DateTime.Now - readStart).TotalMilliseconds)); //ReadVoxel(voxelMap, position, position + (direction * NaniteConstructionManager.Settings.MiningRadius * NaniteConstructionManager.Settings.MiningDepth), miningItems, allowedOreList); } } Logging.Instance.WriteLine(string.Format("MINING Hammer Read Voxel Complete: {0}ms", (DateTime.Now - start).TotalMilliseconds)); Dictionary <MyVoxelMaterialDefinition, List <NaniteMiningItem> > oreList = new Dictionary <MyVoxelMaterialDefinition, List <NaniteMiningItem> >(); Dictionary <Vector3D, NaniteMiningItem> oreLocations = new Dictionary <Vector3D, NaniteMiningItem>(); foreach (var item in miningItems.Values) { var def = MyDefinitionManager.Static.GetVoxelMaterialDefinition(item.VoxelMaterial); if (!oreList.ContainsKey(def)) { oreList.Add(def, new List <NaniteMiningItem>()); } //if (oreList[def].Count >= 1000) // continue; oreList[def].Add(item); //oreLocations.Add(item.Position, item); } m_oreListCache.Clear(); if (oreList != null) { foreach (var item in oreList) { m_oreListCache.Append(string.Format("{0} - {1:N0} Kg\r\n", item.Key.MinedOre, CalculateAmount(item.Key, item.Value.Sum(x => x.Amount)))); } } //using (LocationLock.AcquireExclusiveUsing()) //m_oreLocations = oreLocations; using (Lock.AcquireExclusiveUsing()) m_oreList = oreList; Logging.Instance.WriteLine(string.Format("MINING Hammer Scan Complete: {0}ms ({1} groups, {2} items)", (DateTime.Now - start).TotalMilliseconds, oreList.Count, oreList.Sum(x => x.Value.Count))); } catch (Exception ex) { Logging.Instance.WriteLine(string.Format("ScanVoxelWork() Error: {0}", ex.ToString())); } }
protected IList <Object> GetObjectsRetry(IList <IObjRef> orisToGet, CacheDirective cacheDirective, out bool doAnotherRetry) { doAnotherRetry = false; Lock readLock = ReadLock; if (cacheDirective.HasFlag(CacheDirective.FailEarly)) { readLock.Lock(); try { return(CreateResult(orisToGet, cacheDirective, true)); } finally { readLock.Unlock(); } } List <IObjRef> orisToLoad = new List <IObjRef>(); int cacheVersionBeforeLongTimeAction = WaitForConcurrentReadFinish(orisToGet, orisToLoad); if (orisToLoad.Count == 0) { // Everything found in the cache. We STILL hold the readlock so we can immediately create the result // We already even checked the version. So we do not bother version anymore here try { return(CreateResult(orisToGet, cacheDirective, false)); } finally { readLock.Unlock(); } } CacheDirective parentCacheDirective = CacheDirective.None; if (cacheDirective.HasFlag(CacheDirective.FailInCacheHierarchy)) { parentCacheDirective = CacheDirective.FailEarly; } Parent.GetObjects(orisToLoad, this, parentCacheDirective); // Objects do not have to be put, because their were already // added by the parent to this cache readLock.Lock(); try { int cacheVersionAfterLongTimeAction = changeVersion; if (cacheVersionAfterLongTimeAction != cacheVersionBeforeLongTimeAction) { // Another thread did some changes (possibly DataChange-Remove actions) // We have to ensure that our result-scope is still valid // We return null to allow a further full retry of getObjects() doAnotherRetry = true; return(null); } return(CreateResult(orisToGet, cacheDirective, false)); } finally { readLock.Unlock(); } }
internal void Initialize() { #if CORE || GDI || WPF if (_importedImage != null) { ImportedImageJpeg iiJpeg = _importedImage as ImportedImageJpeg; // In PDF there are two formats: JPEG and PDF bitmap. if (iiJpeg != null) { _format = XImageFormat.Jpeg; } else { _format = XImageFormat.Png; } return; } #endif #if CORE_WITH_GDI if (_gdiImage != null) { // ImageFormat has no overridden Equals function. string guid; try { Lock.EnterGdiPlus(); guid = _gdiImage.RawFormat.Guid.ToString("B").ToUpper(); } finally { Lock.ExitGdiPlus(); } switch (guid) { case "{B96B3CAA-0728-11D3-9D7B-0000F81EF32E}": // memoryBMP case "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}": // bmp case "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}": // png _format = XImageFormat.Png; break; case "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}": // jpeg _format = XImageFormat.Jpeg; break; case "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}": // gif _format = XImageFormat.Gif; break; case "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}": // tiff _format = XImageFormat.Tiff; break; case "{B96B3CB5-0728-11D3-9D7B-0000F81EF32E}": // icon _format = XImageFormat.Icon; break; case "{B96B3CAC-0728-11D3-9D7B-0000F81EF32E}": // emf case "{B96B3CAD-0728-11D3-9D7B-0000F81EF32E}": // wmf case "{B96B3CB2-0728-11D3-9D7B-0000F81EF32E}": // exif case "{B96B3CB3-0728-11D3-9D7B-0000F81EF32E}": // photoCD case "{B96B3CB4-0728-11D3-9D7B-0000F81EF32E}": // flashPIX default: throw new InvalidOperationException("Unsupported image format."); } return; } #endif #if GDI if (_gdiImage != null) { // ImageFormat has no overridden Equals function. string guid; try { Lock.EnterGdiPlus(); guid = _gdiImage.RawFormat.Guid.ToString("B").ToUpper(); } finally { Lock.ExitGdiPlus(); } switch (guid) { case "{B96B3CAA-0728-11D3-9D7B-0000F81EF32E}": // memoryBMP case "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}": // bmp case "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}": // png _format = XImageFormat.Png; break; case "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}": // jpeg _format = XImageFormat.Jpeg; break; case "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}": // gif _format = XImageFormat.Gif; break; case "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}": // tiff _format = XImageFormat.Tiff; break; case "{B96B3CB5-0728-11D3-9D7B-0000F81EF32E}": // icon _format = XImageFormat.Icon; break; case "{B96B3CAC-0728-11D3-9D7B-0000F81EF32E}": // emf case "{B96B3CAD-0728-11D3-9D7B-0000F81EF32E}": // wmf case "{B96B3CB2-0728-11D3-9D7B-0000F81EF32E}": // exif case "{B96B3CB3-0728-11D3-9D7B-0000F81EF32E}": // photoCD case "{B96B3CB4-0728-11D3-9D7B-0000F81EF32E}": // flashPIX default: throw new InvalidOperationException("Unsupported image format."); } return; } #endif #if WPF #if !SILVERLIGHT if (_wpfImage != null) { //string filename = GetImageFilename(_wpfImage); // WPF treats all images as images. // We give JPEG images a special treatment. // Test if it's a JPEG. bool isJpeg = IsJpeg; // TestJpeg(filename); if (isJpeg) { _format = XImageFormat.Jpeg; return; } string pixelFormat = _wpfImage.Format.ToString(); switch (pixelFormat) { case "Bgr32": case "Bgra32": case "Pbgra32": _format = XImageFormat.Png; break; //case "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}": // jpeg // format = XImageFormat.Jpeg; // break; //case "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}": // gif case "BlackWhite": case "Indexed1": case "Indexed4": case "Indexed8": case "Gray8": _format = XImageFormat.Gif; break; //case "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}": // tiff // format = XImageFormat.Tiff; // break; //case "{B96B3CB5-0728-11D3-9D7B-0000F81EF32E}": // icon // format = XImageFormat.Icon; // break; //case "{B96B3CAC-0728-11D3-9D7B-0000F81EF32E}": // emf //case "{B96B3CAD-0728-11D3-9D7B-0000F81EF32E}": // wmf //case "{B96B3CB2-0728-11D3-9D7B-0000F81EF32E}": // exif //case "{B96B3CB3-0728-11D3-9D7B-0000F81EF32E}": // photoCD //case "{B96B3CB4-0728-11D3-9D7B-0000F81EF32E}": // flashPIX default: Debug.Assert(false, "Unknown pixel format: " + pixelFormat); _format = XImageFormat.Gif; break; // throw new InvalidOperationException("Unsupported image format."); } } #else if (_wpfImage != null) { // TODO improve implementation for Silverlight. //string pixelFormat = "jpg"; //_wpfImage...Format.ToString(); //string filename = GetImageFilename(_wpfImage); // WPF treats all images as images. // We give JPEG images a special treatment. // Test if it's a JPEG: bool isJpeg = true; // IsJpeg; // TestJpeg(filename); if (isJpeg) { _format = XImageFormat.Jpeg; return; } /* * switch (pixelFormat) * { * case "Bgr32": * case "Bgra32": * case "Pbgra32": * _format = XImageFormat.Png; * break; * * //case "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}": // jpeg * // format = XImageFormat.Jpeg; * // break; * * //case "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}": // gif * case "BlackWhite": * case "Indexed1": * case "Indexed4": * case "Indexed8": * case "Gray8": * _format = XImageFormat.Gif; * break; * * //case "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}": // tiff * // format = XImageFormat.Tiff; * // break; * * //case "{B96B3CB5-0728-11D3-9D7B-0000F81EF32E}": // icon * // format = XImageFormat.Icon; * // break; * * //case "{B96B3CAC-0728-11D3-9D7B-0000F81EF32E}": // emf * //case "{B96B3CAD-0728-11D3-9D7B-0000F81EF32E}": // wmf * //case "{B96B3CB2-0728-11D3-9D7B-0000F81EF32E}": // exif * //case "{B96B3CB3-0728-11D3-9D7B-0000F81EF32E}": // photoCD * //case "{B96B3CB4-0728-11D3-9D7B-0000F81EF32E}": // flashPIX * * default: * Debug.Assert(false, "Unknown pixel format: " + pixelFormat); * _format = XImageFormat.Gif; * break;// throw new InvalidOperationException("Unsupported image format."); * } */ } #endif #endif }
/// <summary> /// 保存数据 /// </summary> /// <param name="mess">消息队列</param> public void Save(System.Messaging.Message mess) { ServerAnalys serverAnalys = new ServerAnalys(this.WsDownvalue ,this.WsUpvalue,this.CODownvalue,this.COUpvalue); using (Lock l = new Lock(syncSave, 60000, false))//lock超时为1分钟 { try { string tilte = mess.Label; int count = mess.Body.ToString().Split('\n').Length; string[] tiltes = tilte.Split(','); if (tiltes.Length < 5 || tiltes[0].Trim().Length == 0 || tiltes[1].Trim().Length == 0) { Log.Write("非法连接-->" + tilte); return; } //接受新数据事件已经没用,因此刘刚于2010-1-28日注释掉。 //if (ReciveNewDataEvent != null) // ReciveNewDataEvent(mess); CacheModel cCheck = CacheDataList.Find(cd => (cd.CoalCode == tiltes[0].Trim() && cd.CIP != tiltes[3])); if (cCheck != null) { Log.Write("CoalCode-->" + tiltes[0] + "已经存在,拒绝连接!"); return; } string coalCode = tiltes[0]; if (userGB)//启用用户设置的瓦斯、一氧化碳的最大值分析 { if (mess.Body.ToString().Contains("Ï"))//分析数据 { //if (tiltes[4].ToString() == "MinuteAnaly")//分钟数据 //{ // SaveMinRealDev(tiltes, mess.Body.ToString(), this.WsDownvalue, this.WsUpvalue, this.CODownvalue, this.COUpvalue); //} } else { SaveRealDev(tiltes, mess.Body.ToString(), this.WsDownvalue, this.WsUpvalue, this.CODownvalue, this.COUpvalue); } userGB = false; } if (tiltes[4].ToLower() == "true") { if (mess.Body.ToString().Contains("Ï"))//分析数据 { //if (tiltes[4].ToString() == "MinuteAnaly")//分钟数据 //{ // SaveMinRealDev(tiltes, mess.Body.ToString(), this.WsDownvalue, this.WsUpvalue, this.CODownvalue, this.COUpvalue); //} } else//每笔数据 { SaveRealDev(tiltes, mess.Body.ToString(), this.WsDownvalue, this.WsUpvalue, this.CODownvalue, this.COUpvalue); } //SaveRealDev(tiltes, mess.Body.ToString(), this.WsDownvalue, this.WsUpvalue, this.CODownvalue, this.COUpvalue); } if (tiltes.Length == 6) { if (tiltes[5] == "AlarmAnaly") { AlarmAnalydata(coalCode, tiltes[5], mess.Body.ToString()); } else { SaveAnalyData(coalCode, tiltes[5], mess.Body.ToString());//保存客户端上传分析数据 } return; } CacheModel cacheMod = CacheDataList.FindLast(cache => cache.CoalCode == coalCode); // SaveCoalItems(tiltes[1]); if (cacheMod != null) { cacheMod.DataCount += count; count = cacheMod.DataCount; } CacheDataList.Add(new CacheModel { CoalCode = coalCode, Datas = mess.Body.ToString(), // serverAnalys.MessageAnalys(mess.Body.ToString()), DataCount = count, CoalName = tiltes[1], CIP = tiltes[3], Atime = DateTime.Now }); if (count > InitConfig.CountCanSave) { string datas = string.Empty; List<CacheModel> tCacheModels = CacheDataList.FindAll(cache => cache.CoalCode == coalCode); foreach (CacheModel cm in tCacheModels) { datas += cm.Datas; CacheDataList.Remove(cm); } string filePath = dtsPath + "\\" + DateTime.Now.ToString("yyyyMMddHHmmssfff_") + coalCode + ".txt"; UseDtsSave(filePath, coalCode, datas); } } catch (Exception ex) { Tcs.Libary.Log.Write(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ex.ToString()); } } }
protected HubMessage ParseMessage(string raw) { raw = raw.Replace(this.Seperator, ""); HubMessage msg = new HubMessage(hub, raw); if (!string.IsNullOrEmpty(raw)) { switch (raw[0]) { case '$': int pos; string cmd = null; if ((pos = raw.IndexOf(' ')) != -1) cmd = raw.Substring(0, pos).ToLower(); else { if (raw.Length >= 10) break; cmd = raw.ToLower(); } if (cmd == null || cmd.Equals(string.Empty)) break; switch (cmd) { case "$lock": msg = new Lock(hub, raw); break; case "$supports": msg = new Supports(hub, raw); break; case "$hubname": msg = new HubNmdc.HubName(hub, raw); break; case "$hello": msg = new Hello(hub, raw); break; case "$myinfo": msg = new MyINFO(hub, raw); break; case "$nicklist": msg = new NickList(hub, raw); break; case "$oplist": msg = new OpList(hub, raw); break; case "$to:": msg = new To(hub, raw); break; case "$quit": msg = new Quit(hub, raw); break; case "$getpass": msg = new GetPass(hub, raw); break; case "$logedin": msg = new LogedIn(hub, raw); break; case "$validatedenide": msg = new ValidateDenide(hub, raw); break; case "$forcemove": msg = new ForceMove(hub, raw); break; case "$connecttome": msg = new ConnectToMe(hub, raw); break; case "$revconnecttome": msg = new RevConnectToMe(hub, raw); break; case "$search": msg = new Search(hub, raw); break; case "$sr": msg = new SR(hub, raw); break; } break; default: // No command. Assume MainChat. msg = new MainChat(hub, raw); break; } } return msg; }
public WriteLock(Lock @lock) { this._isDisposed = 0; this._lock = @lock; this._lock.EnterWriteLock(); }
internal MockLock(MockLockFactoryWrapper outerInstance, Lock @delegate, string name) { this.OuterInstance = outerInstance; this.DelegateLock = @delegate; this.Name = name; }
internal WriteLock(Lock @lock) { _isDisposed = 0; _lock = @lock; _lock.EnterWriteLock(); }
/// <exception cref="CouchbaseBootstrapException">Condition.</exception> public override void LoadConfig() { Lock.EnterWriteLock(); try { Log.Info("o3-Creating the Servers list using rev#{0}", BucketConfig.Rev); var clientBucketConfig = ClientConfig.BucketConfigs[BucketConfig.Name]; var searchUris = new ConcurrentBag <FailureCountingUri>(); var queryUris = new ConcurrentBag <FailureCountingUri>(); var analyticsUris = new ConcurrentBag <FailureCountingUri>(); var servers = new Dictionary <IPAddress, IServer>(); var nodes = BucketConfig.GetNodes(); foreach (var adapter in nodes) { var endpoint = adapter.GetIPEndPoint(clientBucketConfig.UseSsl); try { IServer server; if (adapter.IsSearchNode) { var uri = UrlUtil.GetFailureCountinSearchBaseUri(adapter, clientBucketConfig); searchUris.Add(uri); } if (adapter.IsQueryNode) { var uri = UrlUtil.GetFailureCountingBaseUri(adapter, clientBucketConfig); queryUris.Add(uri); } if (adapter.IsAnalyticsNode) { var uri = UrlUtil.GetFailureCountingAnalyticsUri(adapter, clientBucketConfig); analyticsUris.Add(uri); } if (adapter.IsDataNode) //a data node so create a connection pool { var uri = UrlUtil.GetBaseUri(adapter, clientBucketConfig); var poolConfiguration = ClientConfig.BucketConfigs[BucketConfig.Name].ClonePoolConfiguration(uri); var connectionPool = ConnectionPoolFactory(poolConfiguration.Clone(uri), endpoint); var newIoService = IOServiceFactory(connectionPool); server = new Core.Server(newIoService, adapter, ClientConfig, BucketConfig, Transcoder, QueryCache) { SaslFactory = SaslFactory }; server.CreateSaslMechanismIfNotExists(); SupportsEnhancedDurability = newIoService.SupportsEnhancedDurability; SupportsSubdocXAttributes = newIoService.SupportsSubdocXAttributes; SupportsEnhancedAuthentication = newIoService.SupportsEnhancedAuthentication; SupportsKvErrorMap = newIoService.SupportsKvErrorMap; } else { server = new Core.Server(null, adapter, ClientConfig, BucketConfig, Transcoder, QueryCache); } servers.Add(endpoint.Address, server); } catch (Exception e) { Log.Error("Could not add server {0}. Exception: {1}", endpoint, e); } } UpdateServices(servers); //for caching uri's Interlocked.Exchange(ref QueryUris, queryUris); Interlocked.Exchange(ref SearchUris, searchUris); Interlocked.Exchange(ref AnalyticsUris, analyticsUris); var old = Interlocked.Exchange(ref Servers, servers); var vBucketKeyMapper = new VBucketKeyMapper(Servers, BucketConfig.VBucketServerMap, BucketConfig.Rev, BucketConfig.Name); Interlocked.Exchange(ref KeyMapper, vBucketKeyMapper); if (old != null) { foreach (var server in old.Values) { server.Dispose(); } old.Clear(); } } finally { Lock.ExitWriteLock(); } }
/// <summary> /// 根据煤矿编号,检查数据库中是否存在该煤矿表,如果没有就创建 /// </summary> /// <param name="CoalCode"></param> private void CheckDbTableByCoalCode(string CoalCode) { using (Lock l = new Lock(sync, 2000, false)) { string[] CodeTableExists = InitConfig.ExistsCoalCode; string exists = Array.Find(CodeTableExists, coalCode => coalCode == CoalCode); if (string.IsNullOrEmpty(exists)) { // Log.Write("CoalCode Not Exist-->" + CoalCode); try { System.Data.Common.DbDataReader dbReader = DataAccess.ExecuteReader(SQL_CHECKTABLE.Replace("TABLENAME", "TN_PerData_" + CoalCode)); if (!dbReader.HasRows) { dbReader.Close(); string createTableSql = CreateTable.CreateMockSql.Replace("TableCoalCode", CoalCode); createTableSql += CreateTable.CreateMinuteDataSql.Replace("TableCoalCode", CoalCode); int Result = ExecuteSqlByTranscation(createTableSql); //Log.Write("Create Table-->"+CoalCode); if (Result > 0) InitConfig.SaveCoalCode(CoalCode); } //else //{ // Log.Write("CoalCode has Exist-->" + CoalCode); //} } catch (DbException exec) { if (InitConfig.Debug) Log.Write(exec); } catch (System.Xml.XmlException exec) { if (InitConfig.Debug) Log.Write(exec); } catch (Exception exec) { if (InitConfig.Debug) Log.Write(exec); } } } }
/// <summary> /// Loads the most updated configuration creating any resources as needed. /// </summary> /// <param name="bucketConfig">The latest <see cref="IBucketConfig"/> /// that will drive the recreation if the configuration context.</param> /// <param name="force">True to force the reconfiguration.</param> public override void LoadConfig(IBucketConfig bucketConfig, bool force = false) { try { Lock.EnterWriteLock(); var nodes = bucketConfig.GetNodes(); if (BucketConfig == null || !nodes.AreEqual(_bucketConfig.GetNodes()) || !Servers.Any() || force) { Log.Info("o1-Creating the Servers {0} list using rev#{1}", nodes.Count, bucketConfig.Rev); var searchUris = new ConcurrentBag <FailureCountingUri>(); var queryUris = new ConcurrentBag <FailureCountingUri>(); var analyticsUris = new ConcurrentBag <FailureCountingUri>(); var clientBucketConfig = ClientConfig.BucketConfigs[bucketConfig.Name]; var servers = new Dictionary <IPAddress, IServer>(); foreach (var adapter in nodes) { var endpoint = adapter.GetIPEndPoint(clientBucketConfig.UseSsl); try { Log.Info("Creating node {0} for rev#{1}", endpoint, bucketConfig.Rev); IServer server; if (adapter.IsSearchNode) { var uri = UrlUtil.GetFailureCountinSearchBaseUri(adapter, clientBucketConfig); searchUris.Add(uri); } if (adapter.IsQueryNode) { var uri = UrlUtil.GetFailureCountingBaseUri(adapter, clientBucketConfig); queryUris.Add(uri); } if (adapter.IsAnalyticsNode) { var uri = UrlUtil.GetFailureCountingAnalyticsUri(adapter, clientBucketConfig); analyticsUris.Add(uri); } if (adapter.IsDataNode) //a data node so create a connection pool { var uri = UrlUtil.GetBaseUri(adapter, clientBucketConfig); var poolConfiguration = ClientConfig.BucketConfigs[BucketConfig.Name].ClonePoolConfiguration(uri); var connectionPool = ConnectionPoolFactory(poolConfiguration.Clone(uri), endpoint); var ioService = IOServiceFactory(connectionPool); server = new Core.Server(ioService, adapter, ClientConfig, bucketConfig, Transcoder, QueryCache) { SaslFactory = SaslFactory }; server.CreateSaslMechanismIfNotExists(); SupportsEnhancedDurability = ioService.SupportsEnhancedDurability; SupportsSubdocXAttributes = ioService.SupportsSubdocXAttributes; SupportsEnhancedAuthentication = ioService.SupportsEnhancedAuthentication; SupportsKvErrorMap = ioService.SupportsKvErrorMap; } else { server = new Core.Server(null, adapter, ClientConfig, bucketConfig, Transcoder, QueryCache); } servers.Add(endpoint.Address, server); } catch (Exception e) { Log.Error("Could not add server {0} for rev#{1}. Exception: {2}", endpoint, bucketConfig.Rev, e); } } UpdateServices(servers); //for caching uri's Interlocked.Exchange(ref QueryUris, queryUris); Interlocked.Exchange(ref SearchUris, searchUris); Interlocked.Exchange(ref AnalyticsUris, analyticsUris); var old = Interlocked.Exchange(ref Servers, servers); Log.Info("Creating the KeyMapper list using rev#{0}", bucketConfig.Rev); var vBucketKeyMapper = new VBucketKeyMapper(Servers, bucketConfig.VBucketServerMap, bucketConfig.Rev, bucketConfig.Name); Interlocked.Exchange(ref KeyMapper, vBucketKeyMapper); Interlocked.Exchange(ref _bucketConfig, bucketConfig); if (old != null) { foreach (var server in old.Values) { Log.Info("Disposing node {0} from rev#{1}", server.EndPoint, server.Revision); server.Dispose(); } old.Clear(); } } else { if (BucketConfig == null || !BucketConfig.IsVBucketServerMapEqual(bucketConfig) || force) { Log.Info("Creating the KeyMapper list using rev#{0}", bucketConfig.Rev); var vBucketKeyMapper = new VBucketKeyMapper(Servers, bucketConfig.VBucketServerMap, bucketConfig.Rev, bucketConfig.Name); Interlocked.Exchange(ref KeyMapper, vBucketKeyMapper); Interlocked.Exchange(ref _bucketConfig, bucketConfig); } //only the revision changed so update to it if (bucketConfig.Rev > BucketConfig.Rev) { Log.Info("Only the revision changed from using rev#{0} to rev#{1}", BucketConfig.Rev, bucketConfig.Rev); BucketConfig.Rev = bucketConfig.Rev; } } } catch (Exception e) { Log.Error(e); } finally { Lock.ExitWriteLock(); } }
public virtual void VisitLock(Lock Lock) { if (Lock == null) return; this.VisitExpression(Lock.Guard); this.VisitBlock(Lock.Body); }
public override void ParallelUpdate(List <IMyCubeGrid> gridList, List <IMySlimBlock> gridBlocks) { try { if (!IsEnabled()) { PotentialTargetList.Clear(); return; } // Add foreach (var beaconBlock in NaniteConstructionManager.BeaconList.Where(x => x is NaniteBeaconDeconstruct && Vector3D.DistanceSquared(m_constructionBlock.ConstructionBlock.GetPosition(), x.BeaconBlock.GetPosition()) < m_maxDistance * m_maxDistance)) { IMyCubeBlock item = (IMyCubeBlock)beaconBlock.BeaconBlock; if (gridList.Contains(item.CubeGrid)) { continue; } MyRelationsBetweenPlayerAndBlock relation = item.GetUserRelationToOwner(m_constructionBlock.ConstructionBlock.OwnerId); if (!(relation == MyRelationsBetweenPlayerAndBlock.Owner || relation == MyRelationsBetweenPlayerAndBlock.FactionShare || (MyAPIGateway.Session.CreativeMode && relation == MyRelationsBetweenPlayerAndBlock.NoOwnership))) { continue; } if (m_validBeaconedGrids.FirstOrDefault(x => x.GridsProcessed.Contains(item.CubeGrid)) != null) { continue; } NaniteDeconstructionGrid deconstruct = new NaniteDeconstructionGrid(item.CubeGrid); m_validBeaconedGrids.Add(deconstruct); CreateGridStack(deconstruct, (MyCubeGrid)item.CubeGrid, (MyCubeBlock)item); using (Lock.AcquireExclusiveUsing()) { foreach (var slimBlock in deconstruct.RemoveList) { if (!PotentialTargetList.Contains(slimBlock)) { PotentialTargetList.Add(slimBlock); } } } deconstruct.RemoveList.Clear(); } CheckAreaBeacons(); if (PotentialTargetList.Count > 0) { using (Lock.AcquireExclusiveUsing()) { foreach (IMySlimBlock item in PotentialTargetList.ToList()) { if (item.CubeGrid.Closed || item.IsDestroyed || item.IsFullyDismounted || (item.FatBlock != null && item.FatBlock.Closed)) { PotentialTargetList.Remove(item); } if (EntityHelper.GetDistanceBetweenBlockAndSlimblock((IMyCubeBlock)m_constructionBlock.ConstructionBlock, item) > m_maxDistance) { PotentialTargetList.Remove(item); } } //m_potentialTargetList = m_potentialTargetList.OrderBy(x => GetBlockConnections((IMySlimBlock)(x))).ToList(); } } else if (TargetList.Count == 0 && PotentialTargetList.Count == 0) { m_validBeaconedGrids.Clear(); } } catch (Exception ex) { Logging.Instance.WriteLine(string.Format("Parallel Erorr: {0}", ex.ToString())); } }
public override Statement VisitLock(Lock Lock) { if (Lock == null) return null; Expression g = Lock.Guard = this.VisitExpression(Lock.Guard); TypeNode t = g == null ? SystemTypes.Object : this.typeSystem.Unwrap(g.Type); if (t.IsValueType) this.HandleError(g, Error.LockNeedsReference, this.GetTypeName(t)); bool savedInsideTryBlock = this.insideTryBlock; this.insideTryBlock = true; Lock.Body = this.VisitBlock(Lock.Body); this.insideTryBlock = savedInsideTryBlock; return Lock; }
public override void FindTargets(ref Dictionary <string, int> available) { m_lastInvalidTargetReason = ""; if (!IsEnabled()) { return; } if (TargetList.Count >= GetMaximumTargets()) { if (PotentialTargetList.Count > 0) { m_lastInvalidTargetReason = "Maximum targets reached. Add more upgrades!"; } return; } using (Lock.AcquireExclusiveUsing()) { foreach (IMySlimBlock item in PotentialTargetList.ToList()) { if (m_constructionBlock.IsUserDefinedLimitReached()) { m_lastInvalidTargetReason = "User defined maximum nanite limit reached"; return; } if (TargetList.Contains(item)) { continue; } if (!NaniteConstructionPower.HasRequiredPowerForNewTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock, this)) { m_lastInvalidTargetReason = "Insufficient power for another target."; break; } if (item.CubeGrid.Closed || item.IsDestroyed || item.IsFullyDismounted || (item.FatBlock != null && item.FatBlock.Closed)) { m_lastInvalidTargetReason = "Potential target is destroyed"; continue; } var blockList = NaniteConstructionManager.GetConstructionBlocks((IMyCubeGrid)m_constructionBlock.ConstructionBlock.CubeGrid); bool found = false; foreach (var block in blockList) { if (block.Targets.First(x => x is NaniteDeconstructionTargets).TargetList.Contains(item as IMySlimBlock)) { found = true; break; } } if (found) { m_lastInvalidTargetReason = "Another factory has this block as a target"; continue; } /* * var blocks = NaniteConstructionManager.NaniteBlocks.Select(x => x.Value).Where(y => y.ConstructionBlock.CubeGrid == m_constructionBlock.ConstructionBlock.CubeGrid && y.ConstructionBlock != m_constructionBlock.ConstructionBlock); * Logging.Instance.WriteLine(string.Format("Count: {0}", blocks.Count())); * var found = blocks.FirstOrDefault(x => x.Targets.First(y => y is NaniteDeconstructionTargets).TargetList.Contains(item)) != null; * if (found) * { * Logging.Instance.WriteLine("Found"); * continue; * } */ PotentialTargetList.Remove(item); TargetList.Add(item); var def = item.BlockDefinition as MyCubeBlockDefinition; Logging.Instance.WriteLine(string.Format("ADDING Deconstruction Target: conid={0} subtypeid={1} entityID={2} position={3}", m_constructionBlock.ConstructionBlock.EntityId, def.Id.SubtypeId, item.FatBlock != null ? item.FatBlock.EntityId : 0, item.Position)); if (TargetList.Count >= GetMaximumTargets()) { break; } } } }
public ConditionalWeakTable() { _container = new Container().Resize(); _lock = new Lock(); }
public override void ParallelUpdate(List <IMyCubeGrid> gridList, List <IMySlimBlock> gridBlocks) { using (Lock.AcquireExclusiveUsing()) PotentialTargetList.Clear(); DateTime start = DateTime.Now; List <object> finalAddList = new List <object>(); int listCount = 0; foreach (var miningBlock in NaniteConstructionManager.MiningList.Where(x => x.IsWorking && Vector3D.DistanceSquared(m_constructionBlock.ConstructionBlock.GetPosition(), x.MiningBlock.GetPosition()) < m_maxDistance * m_maxDistance).OrderBy(x => rnd.Next(100))) { IMyCubeBlock item = (IMyCubeBlock)miningBlock.MiningBlock; MyRelationsBetweenPlayerAndBlock relation = item.GetUserRelationToOwner(m_constructionBlock.ConstructionBlock.OwnerId); if (!(relation == MyRelationsBetweenPlayerAndBlock.Owner || relation == MyRelationsBetweenPlayerAndBlock.FactionShare || (MyAPIGateway.Session.CreativeMode && relation == MyRelationsBetweenPlayerAndBlock.NoOwnership))) { continue; } if (!((IMyFunctionalBlock)item).Enabled) { continue; } if (miningBlock.OreList == null || miningBlock.OreList.Count < 1) { continue; } int sum = miningBlock.OreList.Sum(x => x.Value.Count); Dictionary <MyVoxelMaterialDefinition, List <NaniteMiningItem> > lookup = null; using (miningBlock.Lock.AcquireExclusiveUsing()) { lookup = miningBlock.OreList.ToDictionary(x => x.Key, x => x.Value); } List <object> addList = new List <object>(); int count = 0; int pos = 0; while (true) { var group = lookup.ElementAt(count % miningBlock.OreList.Count); if (pos < group.Value.Count) { addList.Insert(0, group.Value[pos]); } count++; if (count % miningBlock.OreList.Count == 0) { pos++; } if (count >= 1000) { break; } if (count >= sum) { break; } } DistributeList(addList, finalAddList, listCount); listCount++; if (listCount > 5) { break; } } var listToAdd = finalAddList.Take(1000).ToList(); listToAdd.Reverse(); using (Lock.AcquireExclusiveUsing()) { PotentialTargetList.AddRange(listToAdd); } //Logging.Instance.WriteLine(string.Format("ParallelUpdate() took {0} ms", (DateTime.Now - start).TotalMilliseconds)); }
void case_1009() #line 6746 "cs-parser.jay" { Error_SyntaxError (yyToken); yyVal = new Lock ((Expression) yyVals[-1+yyTop], null, GetLocation (yyVals[-3+yyTop])); lbag.AddStatement (yyVal, GetLocation (yyVals[-2+yyTop])); }
public override void FindTargets(ref Dictionary <string, int> available) { if (!IsEnabled()) { return; } if (TargetList.Count >= GetMaximumTargets()) { if (PotentialTargetList.Count > 0) { m_lastInvalidTargetReason = "Maximum targets reached. Add more upgrades!"; } return; } DateTime start = DateTime.Now; using (Lock.AcquireExclusiveUsing()) { if (m_constructionBlock.IsUserDefinedLimitReached()) { m_lastInvalidTargetReason = "User defined maximum nanite limit reached"; return; } //foreach (NaniteMiningItem item in PotentialTargetList) for (int r = PotentialTargetList.Count - 1; r >= 0; r--) { var item = (NaniteMiningItem)PotentialTargetList[r]; if (TargetList.Contains(item)) { continue; } if (m_globalPositionList.Contains(item.Position)) { m_lastInvalidTargetReason = "Another factory has this voxel as a target"; continue; } var blockList = NaniteConstructionManager.GetConstructionBlocks((IMyCubeGrid)m_constructionBlock.ConstructionBlock.CubeGrid); bool found = false; foreach (var block in blockList) { // This can be sped up if necessary by indexing items by position if (block.GetTarget <NaniteMiningTargets>().TargetList.FirstOrDefault(x => ((NaniteMiningItem)x).Position == item.Position) != null) { found = true; break; } } if (found) { m_lastInvalidTargetReason = "Another factory has this voxel as a target"; continue; } if (!NaniteMining.CheckVoxelContent(item.VoxelId, item.Position)) { continue; } if (Vector3D.DistanceSquared(m_constructionBlock.ConstructionBlock.GetPosition(), item.Position) < m_maxDistance * m_maxDistance && NaniteConstructionPower.HasRequiredPowerForNewTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock, this)) { Logging.Instance.WriteLine(string.Format("ADDING Mining Target: conid={0} pos={1} type={2}", m_constructionBlock.ConstructionBlock.EntityId, item.Position, MyDefinitionManager.Static.GetVoxelMaterialDefinition(item.VoxelMaterial).MinedOre)); //PotentialTargetList.Remove(item); TargetList.Add(item); m_globalPositionList.Add(item.Position); if (TargetList.Count >= GetMaximumTargets()) { break; } } } } //Logging.Instance.WriteLine(string.Format("FindTargets took {0}ms", (DateTime.Now - start).TotalMilliseconds)); }
void InitPuzzle() { //SetupWires-- for (int ctr = 0; ctr < diffLength; ctr++) { //Create Object and place it in the given placeholder GameObject obj = Instantiate(wirePrefab, puzzleCan) as GameObject; //Set the position obj.transform.position = wirePlaceholders [ctr].position; //Get the Wire Script Wire w = obj.GetComponentInChildren <Wire>(); //Assgin the var id in the wire script w.wireIDLink = ctr + 1; //Add it to our list collection wires.Add(w); } //Shuffle the wires-- Shuffle <Wire>(wires); //Setup Locks-- for (int ctr = 0; ctr < diffLength; ctr++) { GameObject obj = Instantiate(lockPrefab, puzzleCan) as GameObject; //Set the position obj.transform.position = lockPlaceholders [ctr].position; //Get scripts attached to the gameobject Lock r = obj.GetComponent <Lock> (); //Set the ids r.lockID = ctr + 1; //Add it to our list collection realLocks.Add(r); //calulate needed sum r.neededSum = wires[ctr].wireIDLink + r.lockID; //Set Text UI if (difficulty == 3) { neededNumberText[ctr].text = "?"; } else { neededNumberText[ctr].text = r.neededSum.ToString(); } r.textCSum = currentNumberText[ctr]; } //Setup Connections-- for (int ctr = 0; ctr < diffLength; ctr++) { //Create Object and place it in the given placeholder GameObject obj = Instantiate(connectionPrefab, puzzleCan) as GameObject; //Set the position obj.transform.position = connectionPlaceholders [ctr].position; //Get the Connection Script Connection c = obj.GetComponentInChildren <Connection>(); //set values c.assginedLock = realLocks [ctr]; //add it to collection inputConnections.Add(c); } }
public virtual Differences VisitLock(Lock lock1, Lock lock2){ Differences differences = new Differences(lock1, lock2); if (lock1 == null || lock2 == null){ if (lock1 != lock2) differences.NumberOfDifferences++; else differences.NumberOfSimilarities++; return differences; } Lock changes = (Lock)lock2.Clone(); Lock deletions = (Lock)lock2.Clone(); Lock insertions = (Lock)lock2.Clone(); Differences diff = this.VisitBlock(lock1.Body, lock2.Body); if (diff == null){Debug.Assert(false); return differences;} changes.Body = diff.Changes as Block; deletions.Body = diff.Deletions as Block; insertions.Body = diff.Insertions as Block; Debug.Assert(diff.Changes == changes.Body && diff.Deletions == deletions.Body && diff.Insertions == insertions.Body); differences.NumberOfDifferences += diff.NumberOfDifferences; differences.NumberOfSimilarities += diff.NumberOfSimilarities; diff = this.VisitExpression(lock1.Guard, lock2.Guard); if (diff == null){Debug.Assert(false); return differences;} changes.Guard = diff.Changes as Expression; deletions.Guard = diff.Deletions as Expression; insertions.Guard = diff.Insertions as Expression; Debug.Assert(diff.Changes == changes.Guard && diff.Deletions == deletions.Guard && diff.Insertions == insertions.Guard); differences.NumberOfDifferences += diff.NumberOfDifferences; differences.NumberOfSimilarities += diff.NumberOfSimilarities; if (differences.NumberOfDifferences == 0){ differences.Changes = null; differences.Deletions = null; differences.Insertions = null; }else{ differences.Changes = changes; differences.Deletions = deletions; differences.Insertions = insertions; } return differences; }
public virtual object Visit(Lock lockStatement) { return(null); }
public virtual Statement VisitLock(Lock Lock, Lock changes, Lock deletions, Lock insertions){ this.UpdateSourceContext(Lock, changes); if (Lock == null) return changes; if (changes != null){ if (deletions == null || insertions == null) Debug.Assert(false); else{ } }else if (deletions != null) return null; return Lock; }
public void Dispose() { Lock.ExitReadLock(); }