private static Map LoadOrGet(string name, int id) { Map m; if (!_loadedMaps.ContainsKey(id)) { m = new Map(name, id); _loadedMaps.Add(id, new WeakReference <Map>(m)); return(m); } WeakReference <Map> w = _loadedMaps[id]; if (w.TryGetTarget(out m)) { return(m); } m = new Map(name, id); w.SetTarget(m); return(m); }
internal Pip InternalGetOrSetPip(PipTable table, PipId pipId, PipQueryContext context, Func <PipTable, PipId, PageableStoreId, PipQueryContext, Pip> creator) { Contract.Ensures(Contract.Result <Pip>() != null); lock (this) { Pip pip; if (m_weakPip == null) { pip = creator(table, pipId, StoreId, context); m_weakPip = new WeakReference <Pip>(pip); } else if (!m_weakPip.TryGetTarget(out pip)) { m_weakPip.SetTarget(pip = creator(table, pipId, StoreId, context)); } return(pip); } }
private static Blockset LoadOrGet(string name, int id) { Blockset b; if (!_loadedBlocksets.ContainsKey(id)) { b = new Blockset(name, id); _loadedBlocksets.Add(id, new WeakReference <Blockset>(b)); return(b); } WeakReference <Blockset> w = _loadedBlocksets[id]; if (w.TryGetTarget(out b)) { return(b); } b = new Blockset(name, id); w.SetTarget(b); return(b); }
/// <summary> /// Put an object in the cache; remove older versions of the object if existent /// </summary> /// <param name="pc">The object to put into the cache</param> public void UpdateCache(IPersistenceCapable pc) { ObjectId oid = pc.NDOObjectId; if (lockedObjects.ContainsKey(oid)) { return; } Debug.Assert(pc.NDOObjectState == NDOObjectState.Persistent || pc.NDOObjectState == NDOObjectState.Hollow); WeakReference <IPersistenceCapable> objRef = null; if (objects.TryGetValue(oid, out objRef)) { objRef.SetTarget(pc); } else { objects.Add(pc.NDOObjectId, new WeakReference <IPersistenceCapable>(pc)); } }
private static Layout LoadOrGet(string name, int id) { Layout l; if (!_loadedLayouts.ContainsKey(id)) { l = new Layout(name, id); _loadedLayouts.Add(id, new WeakReference <Layout>(l)); return(l); } WeakReference <Layout> w = _loadedLayouts[id]; if (w.TryGetTarget(out l)) { return(l); } l = new Layout(name, id); w.SetTarget(l); return(l); }
public static SpriteSheet LoadOrGet(string id) { SpriteSheet s; if (!_loadedSheets.ContainsKey(id)) { s = new SpriteSheet(id); _loadedSheets.Add(id, new WeakReference <SpriteSheet>(s)); return(s); } WeakReference <SpriteSheet> w = _loadedSheets[id]; if (w.TryGetTarget(out s)) { return(s); } s = new SpriteSheet(id); w.SetTarget(s); return(s); }
public ModelDefinition GetModelDefinition() { ModelDefinition def; if (_DefinitionCache != null && _DefinitionCache.TryGetTarget(out def)) { return(def); } def = new ModelDefinition(this); if (_DefinitionCache == null) { _DefinitionCache = new WeakReference <ModelDefinition>(def); } else { _DefinitionCache.SetTarget(def); } return(def); }
internal static async Task AccessRouteCache(Func <List <Tuple <BusRoute, string[], string[]> >, bool> action) { List <Tuple <BusRoute, string[], string[]> > routes; var file = await ApplicationData.Current.LocalCacheFolder.GetFileAsync("RouteCache.txt"); if (!SavedRouteCache.TryGetTarget(out routes)) { string encodedText = await FileIO.ReadTextAsync(file); CompactFormatReader reader = new CompactFormatReader(encodedText); routes = DeformatRoutes(reader); } if (action(routes)) { CompactFormatWriter writer = new CompactFormatWriter(); FormatRoutes(routes, writer); await FileIO.WriteTextAsync(file, writer.ToString()); SavedRouteCache.SetTarget(routes); } }
protected async override Task ShowPlaceholder(string path, string key, ImageSource source, bool isLoadingPlaceholder) { await base.ShowPlaceholder(path, key, source, isLoadingPlaceholder); if (isLoadingPlaceholder) { var placeholder = MemoryCache.Get(key)?.Item1; if (placeholder != null) { if (_loadingPlaceholderWeakReference == null) { _loadingPlaceholderWeakReference = new WeakReference <ISelfDisposingBitmapDrawable>(placeholder); } else { _loadingPlaceholderWeakReference.SetTarget(placeholder); } } } }
public Task <T> Enqueue <T>(Func <Task <T> > asyncFunction) { lock (_locker) { Task <T> resultTask; if (_lastTask.TryGetTarget(out var lastTask)) { resultTask = lastTask .ContinueWith(_ => asyncFunction(), TaskContinuationOptions.ExecuteSynchronously).Unwrap(); } else { resultTask = Task.Run(asyncFunction); } _lastTask.SetTarget(resultTask); return(resultTask); } }
public override void OnEnter(NetworkReader reader, string className, string methodName) { base.OnEnter(reader, className, methodName); _eventStack.TryPeek(out var parent); if (reader != null) { _reader.SetTarget(reader); } else { _reader.TryGetTarget(out reader); } _eventStack.Push(new PacketInteractionCall(parent, className, methodName)); if (parent == null) { Interactions.Add(_eventStack.Peek()); } _eventStack.Peek().PositionOnEnter = (int)reader.Position; }
private Tuple <ulong[], long[]> GetParentOffsets() { Tuple <ulong[], long[]> offsets; if (_fieldParents.TryGetTarget(out offsets)) // get stuff from WeakReference<Tuple<ulong[], long[]>> { return(offsets); } string error; offsets = GetFieldOffsets(_offsetsPath, out error); if (error != null) { _lastError = error; } else { _fieldParents.SetTarget(offsets); } return(offsets); // might be mull if GetFieldOffsets method fails }
private void Initialize() { TypeData cache; if (Cache == null || !Cache.TryGetTarget(out cache)) { var targetType = serializedObject.targetObject.GetType(); if (!ReflectionCache.TryGetValue(targetType, out cache)) { cache = new TypeData(); foreach (var attrib in targetType.GetCustomAttributesData()) { foreach (Type attributeType in AttributeTypes) { if (attrib.AttributeType.IsSubclassOf(attributeType)) { cache.Attributes.Add(attrib); } } } foreach (var member in targetType.GetMembers().OrderBy(m => m.MetadataToken)) { ProcessClassMember(cache, targetType, member); } ReflectionCache[serializedObject.targetObject.GetType()] = cache; } if (Cache != null) { Cache.SetTarget(cache); } else { Cache = new WeakReference <TypeData>(cache); } } }
/// <summary> /// Gets a list that's a "snapshot" of the current state of the collection, ie it's a copy of whatever elements /// are currently in the collection. /// </summary> public List <T> getSnapshot() { Debug.Assert(Thread.CurrentThread.ManagedThreadId == _threadId); List <T> list; // if we have a cached snapshot that's up to date, just use that one if (!_snapshot.TryGetTarget(out list) || _listVersion != _owner._version) { // need to create a new snapshot // if nothing is using the old snapshot, we can clear and reuse the existing list instead // of allocating a brand new list. yay for eco-friendly solutions! int enumCount = _enumeratingCurrentSnapshot; _snapshotId++; _enumeratingCurrentSnapshot = 0; _owner._lock.EnterReadLock(); try { _listVersion = _owner._version; if (list == null || enumCount > 0) { // if enumCount > 0 here that means something is currently using the instance of list. we create a new list // here and "strand" the old list so the enumerator can finish enumerating it in peace. list = new List <T>(_owner._collection); _snapshot.SetTarget(list); } else { // clear & reuse the old list list.Clear(); list.AddRange(_owner._collection); } } finally { _owner._lock.ExitReadLock(); } } return(list); }
public override byte[] GetData() { byte[] buffer; if (_BufferCache != null && _BufferCache.TryGetTarget(out buffer)) { return(buffer); } buffer = Read(); if (_BufferCache == null) { _BufferCache = new WeakReference <byte[]>(buffer); } else { _BufferCache.SetTarget(buffer); } return(buffer); }
public Image GetImage() { Image image; if (_ImageCache != null && _ImageCache.TryGetTarget(out image)) { return(image); } image = ImageConverter.Convert(this); if (_ImageCache == null) { _ImageCache = new WeakReference <Image>(image); } else { _ImageCache.SetTarget(image); } return(image); }
/// <summary> /// This protected initialization method is provided to support the protected /// default constructor. /// </summary> /// <param name="target">Not null. Will be weakly held here.</param> /// <param name="weakOwner">Optional object will determine the weak retention of the /// <paramref name="target"/>.</param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="InvalidOperationException">If this has already been initialized.</exception> protected void Initialize(T target, object weakOwner = null) { if (target == null) { throw new ArgumentNullException(nameof(target)); } if (IsDisposed) { throw new ObjectDisposedException(ToString()); } if (weakOwner == null) { weakOwner = target; } if (weakTarget.TryGetTarget(out _) || (this.weakOwner?.TryGetValue(weakOwner, out _) ?? false)) { throw new InvalidOperationException("Instance has already been initialized."); } weakTarget.SetTarget(target); this.weakOwner.Add(weakOwner, target); }
public static async Task <TranslationServiceClient> GetTranslationServiceClientAsync() { var path = Properties.Settings.Default.CredentialsPath; if (!TranslationServiceClientCache.TryGetTarget(out var tuple) || tuple.CredentialsPath != path) { var client = string.IsNullOrWhiteSpace(path) ? await TranslationServiceClient.CreateAsync() : await new TranslationServiceClientBuilder { CredentialsPath = path } .BuildAsync(); tuple = new TranslationServiceClientTuple { Client = client, CredentialsPath = path }; TranslationServiceClientCache.SetTarget(tuple); } return(tuple.Client); }
protected virtual bool HandleMouseClick(InputState state) { // due to the laziness of IEnumerable, .Where check should be done right before it is triggered for the event. var drawables = MouseDownInputQueue.Intersect(PositionalInputQueue) .Where(t => t.CanReceiveMouseInput && t.ReceiveMouseInputAt(state.Mouse.Position)); var clicked = PropagateMouseButtonEvent(drawables, new ClickEvent(state, Button, MouseDownPosition)); ClickedDrawable.SetTarget(clicked); if (ChangeFocusOnClick) { RequestFocus?.Invoke(clicked); } if (clicked != null) { Logger.Log($"MouseClick handled by {clicked}.", LoggingTarget.Runtime, LogLevel.Debug); } return(clicked != null); }
public static OtherResult GlobalManage(HttpContext context) { var verb = context.GetQueryOptionalTextParameter("Verb"); if (verb != null && verbs.TryGetValue(verb, out var process)) { return(process(context)); } else { #if DEBUG string data = File.ReadAllText(HtmlFileName); #else if (!html.TryGetTarget(out var data)) { data = File.ReadAllText(HtmlFileName); html.SetTarget(data); } #endif return(new Status200Result(data, "text/html")); } }
/// <summary> /// Loads the data as a byte array. /// </summary> /// <returns>The byte array representation of the data.</returns> public byte[] GetDataBuffer() { if (_buffer == null) { throw new InvalidOperationException(); } if (_isDeflated) { if (!_weakInflatedBufferRef.TryGetTarget(out byte[] inflatedBuffer)) { inflatedBuffer = new byte[_actualSize]; BlockCompression.Inflate(_buffer, _actualSize, inflatedBuffer); _weakInflatedBufferRef.SetTarget(inflatedBuffer); } return(inflatedBuffer); } else { return(_buffer); } }
public override string ToString() { string v; if (_StringCache != null && _StringCache.TryGetTarget(out v)) { return(v); } StringBuilder sb = new StringBuilder(); ToString(sb); v = sb.ToString(); if (_StringCache == null) { _StringCache = new WeakReference <string>(v); } else { _StringCache.SetTarget(v); } return(v); }
/// <summary> /// Gets a dynamic view of the underlying cache based on the parameters given. /// </summary> /// <param name="mode">View mode.</param> /// <param name="startKey">Start key of view.</param> /// <param name="endKey">End key of view.</param> /// <param name="tailCount">Number of items to include in view.</param> /// <param name="tailRange">Tail duration function. Takes last item's key and returns a new startKey.</param> /// <returns>An instance of <see cref="ObservableKeyedView"/>.</returns> /// <exception cref="ArgumentException"><paramref name="startKey"/> must be less than or equal to <paramref name="endKey"/>.</exception> public ObservableKeyedView GetView(ObservableKeyedView.ViewMode mode, TKey startKey, TKey endKey, uint tailCount, Func <TKey, TKey> tailRange) { if (this.keyComparer.Compare(startKey, endKey) > 0) { throw new ArgumentException($"startKey ({startKey}) must be less than or equal to endKey ({endKey})."); } var viewKey = Tuple.Create(startKey, endKey, tailCount, tailRange); WeakReference <ObservableKeyedView> weakView = null; ObservableKeyedView view = null; if (this.views.TryGetValue(viewKey, out weakView)) { if (weakView.TryGetTarget(out view)) { return(view); } else { view = new ObservableKeyedView(this, mode, startKey, endKey, tailCount, tailRange); weakView.SetTarget(view); // Sometimes the weak view gets deleted between when we grab it to check // if it has a hard reference and when we actually set the new hard reference // that we just created. If that happens, then the following code makes sure // the weak view gets put back into the collection. this.views[viewKey] = weakView; } } else { view = new ObservableKeyedView(this, mode, startKey, endKey, tailCount, tailRange); weakView = new WeakReference <ObservableKeyedView>(view); this.views.Add(viewKey, weakView); } return(view); }
public static bool IsFromGeneratedCode(this SemanticModel semanticModel, CancellationToken cancellationToken) { ImmutableDictionary <SyntaxTree, bool> table; var tree = semanticModel.SyntaxTree; if (cache.TryGetTarget(out table)) { if (table.ContainsKey(tree)) { return(table[tree]); } } else { table = ImmutableDictionary <SyntaxTree, bool> .Empty; } var result = IsFileNameForGeneratedCode(tree.FilePath) || ContainsAutogeneratedComment(tree, cancellationToken); cache.SetTarget(table.Add(tree, result)); return(result); }
/// <summary> /// Retrieves the target from a <see cref="WeakReference{T}" /> if it has one, or creates an instance of <typeparamref name="T"/> and sets that as the target before returning the instance; /// </summary> /// <typeparam name="T">The type of the target.</typeparam> /// <param name="reference"></param> /// <param name="factoryMethod">The delegate to invoke to create a new target if neccessary. If this is null, then a target is instantiated via <typeparamref name="T" />'s public default constructor.</param> /// <exception cref="ArgumentNullException" /> /// <exception cref="MissingMethodException" /> public static T GetLazilyInitializedTarget <T>(this WeakReference <T> reference, Func <T> factoryMethod = null) where T : class { if (reference == null) { throw new ArgumentNullException(nameof(reference)); } if (!reference.TryGetTarget(out T target)) { if (factoryMethod == null) { target = Activator.CreateInstance <T>(); } else { target = factoryMethod.Invoke(); } reference.SetTarget(target); } return(target); }
/// <summary> /// Asynchronously fetch the item. /// </summary> public async Task <T> Fetch() { T reference; if (_set && _item.TryGetTarget(out reference)) { return(reference); } reference = await GetItem.RunAsync(); if (reference != null) { if (_set) { _item.SetTarget(reference); } else { _set = true; _item = new WeakReference <T>(reference); } } return(reference); }
internal void SetAsset(UnityObject asset) { if (asset == null) { State = NodeState.LoadError; assetRef = null; } else { State = NodeState.Loaded; if (assetRef == null) { assetRef = new WeakReference <UnityObject>(asset); } else { assetRef.SetTarget(asset); } if (refCount > 0 && cachedAsset == null) { cachedAsset = asset; } } }
public void WatchLevelSettings(LevelSettings settings) { var listOfWatchedObjs = new List <FileSystemWatcherManager.WatchedObj>(); foreach (LevelTexture texture in settings.Textures) { listOfWatchedObjs.Add(new WatchedTexture { Parent = this, Texture = texture }); } foreach (ReferencedWad wad in settings.Wads) { listOfWatchedObjs.Add(new WatchedWad { Parent = this, Wad = wad }); } foreach (ReferencedSoundsCatalog catalog in settings.SoundsCatalogs) { listOfWatchedObjs.Add(new WatchedSoundCatalog { Parent = this, SoundsCatalog = catalog }); } foreach (ImportedGeometry importedGeometry in settings.ImportedGeometries) { listOfWatchedObjs.Add(new WatchedImportedGeometry { Parent = this, ImportedGeometry = importedGeometry }); } foreach (ImportedGeometryTexture importedGeometryTexture in settings.ImportedGeometries.SelectMany(geometry => geometry.Textures).Distinct()) { listOfWatchedObjs.Add(new WatchedImportedGeometryTexture { Parent = this, ImportedGeometryTexture = importedGeometryTexture }); } _watcher.UpdateAllFiles(listOfWatchedObjs, () => _settings.SetTarget(settings)); }
protected virtual bool HandleMouseClick(InputState state) { var intersectingQueue = MouseDownInputQueue.Intersect(PositionalInputQueue); setPositionMouseDown(state); // click pass, triggering an OnClick on all drawables up to the first which returns true. // an extra IsHovered check is performed because we are using an outdated queue (for valid reasons which we need to document). var clicked = intersectingQueue.FirstOrDefault(t => t.CanReceiveMouseInput && t.ReceiveMouseInputAt(state.Mouse.Position) && t.TriggerOnClick(state)); ClickedDrawable.SetTarget(clicked); if (ChangeFocusOnClick) { RequestFocus?.Invoke(clicked); } if (ClickedDrawable != null) { Logger.Log($"MouseClick handled by {ClickedDrawable}.", LoggingTarget.Runtime, LogLevel.Debug); } return(ClickedDrawable != null); }
private Dictionary <string, Action <T> > GetBuilders() { if (_columnBuilders != null && _columnBuilders.TryGetTarget(out Dictionary <string, Action <T> > builders)) { return(builders); } else { lock (_builderLock) { if (_columnBuilders == null) { builders = this.InitializeColumnBuilders(); _columnBuilders = new WeakReference <Dictionary <string, Action <T> > >(builders); } else if (!_columnBuilders.TryGetTarget(out builders)) { builders = this.InitializeColumnBuilders(); _columnBuilders.SetTarget(builders); } return(builders); } } }