/// <summary> /// Creates and returns a string representation of this instance. /// </summary> /// <returns> /// The result of calling <see cref="System.Object.ToString" /> on the <see cref="Value" />. /// </returns> /// <exception cref="T:System.NullReferenceException">The <see cref="Value" /> is null.</exception> public override string ToString() { if (_createOnToString) { T value = Value; return(ReferenceEquals(value, null) ? string.Empty : value.ToString()); } object boxed = _boxed; Boxed b = boxed as Boxed; if (b != null) { return(ReferenceEquals(b.Value, null) ? string.Empty : b.Value.ToString()); } ExceptionDispatchInfo edi = boxed as ExceptionDispatchInfo; if (edi != null) { edi.Throw(); // NOTE: Never actually returned return("Value has exception"); } // ReSharper disable once AssignNullToNotNullAttribute return(Resources.ResettableLazy_ToString_ValueNotCreated); }
private void LoadActionParams(BotActionDesc action, object[] args, MyPerTreeBotMemory botMemory) { for (int i = 0; i < args.Length; i++) { var arg = args[i]; if (arg is Boxed <MyStringId> && action.ParametersDesc.ContainsKey(i)) { var parameterDesc = action.ParametersDesc[i]; Boxed <MyStringId> stringId = arg as Boxed <MyStringId>; MyBBMemoryValue value = null; if (botMemory.TryGetFromBlackboard(stringId, out value)) { if (value == null || value.GetType() == parameterDesc.Item1) { action.ActionParams[i] = value; } else { Debug.Assert(false, "Mismatch of types in the blackboard. Did you use a wrong identifier?"); action.ActionParams[i] = null; } } } else { action.ActionParams[i] = arg; } } }
private T CreateValue() { var threadSafeObj = Volatile.Read(ref _threadSafeObj); var lockTaken = false; try { if (threadSafeObj != _usedThreadSafeObj) { Monitor.Enter(threadSafeObj, ref lockTaken); if (_boxed == null) { _boxed = new Boxed(_valueFactory()); _valueFactory = _usedValueFactory; Volatile.Write(ref _threadSafeObj, _usedThreadSafeObj); } } } finally { if (lockTaken) { Monitor.Exit(threadSafeObj); } } return(_boxed.Value); }
/// <summary> /// Initializes a new instance /// of the <see cref="Radischevo.Wahha.Core.LinkBase{T}"/> class /// with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> /// that holds the serialized object data.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> /// that contains contextual information about the source or destination.</param> protected LinkBase(SerializationInfo info, StreamingContext context) { if (info.GetBoolean("serializable")) { _source = (Func <T>)info.GetValue("source", typeof(Func <T>)); } else { if (!info.GetBoolean("dynamicMethod")) { MethodInfo method = (MethodInfo)info.GetValue("sourceMethod", typeof(MethodInfo)); object target = Activator.CreateInstance(method.DeclaringType, true); foreach (FieldInfo field in method.DeclaringType.GetFields()) { field.SetValue(target, info.GetValue("source" + field.Name, field.FieldType)); } _source = (Func <T>)Delegate.CreateDelegate(typeof(Func <T>), target, method); } } _value = (Boxed)info.GetValue("value", typeof(Boxed)); _hasAssignedValue = info.GetBoolean("hasAssignedValue"); _hasLoadedValue = info.GetBoolean("hasLoadedValue"); _tag = info.GetValue("tag", typeof(object)); }
/// <summary> /// Creates and returns a string representation of this instance. /// </summary> /// <returns> /// The result of calling <see cref="System.Object.ToString" /> on the <see cref="Value" />. /// </returns> /// <exception cref="T:System.NullReferenceException">The <see cref="Value" /> is null.</exception> public override string ToString() { if (_createOnToString) { T value = Value; return(ReferenceEquals(value, null) ? string.Empty : value.ToString()); } object boxed = _boxed; Boxed b = boxed as Boxed; if (b != null) { return(ReferenceEquals(b.Value, null) ? string.Empty : b.Value.ToString()); } ExceptionDispatchInfo edi = boxed as ExceptionDispatchInfo; if (edi != null) { edi.Throw(); // NOTE: Never actually returned return("Value has exception"); } return("Value not created"); }
public void TestConcreteConverter() { var converter = new OptionJsonConverter <Boxed <int> >(); Assert.False(converter.CanConvert(Option.None.GetType())); TestOptionsConverter(converter, Option.Some(Boxed.Of(42))); }
public void TestGenericNullRefConverter() { var converter = new GenericOptionJsonConverter(typeof(Maybe <>)); Assert.True(converter.CanConvert(Maybes.None.GetType())); TestOptionsConverter(converter, Maybes.Some(Boxed.Of(42))); }
public void TestGenericOptionConverter() { var converter = new GenericOptionJsonConverter(typeof(Option <>)); Assert.True(converter.CanConvert(Option.None.GetType())); TestOptionsConverter(converter, Option.Some(Boxed.Of(42))); }
private Boxed <RaycastHit2D> getNearestHitByType <Type>(Vector2 inPointToFindFrom, RaycastHit2D[] inHits, System.Func <Type, bool> inAcceptingFilter = null, bool inUseYDistanceOnly = false) where Type : Component { Boxed <RaycastHit2D> theResult = null; float theMinimumDistance = float.MaxValue; foreach (RaycastHit2D theHit in inHits) { //Debug.Log(theHit.collider.name); Type theComponent = theHit.collider.GetComponent <Type>(); if (theComponent && (null == inAcceptingFilter || inAcceptingFilter(theComponent))) { Vector2 thePosition2D = new Vector2(!inUseYDistanceOnly ? theComponent.transform.position.x : 0f, theComponent.transform.position.y); Vector2 theDelta = new Vector2(!inUseYDistanceOnly ? inPointToFindFrom.x : 0f, inPointToFindFrom.y) - thePosition2D; float theDistance = theDelta.magnitude; if (theDistance < theMinimumDistance) { theResult = new Boxed <RaycastHit2D>(theHit); theMinimumDistance = theDistance; } } } //Debug.Log("RESULT: " + theResult.value.collider.name); return(theResult); }
public bool DoSomethingResult(string s, int i) { Console.WriteLine($"Thing: DoSomethingResult({s}, {i})"); Boxed <bool> result = Boxer.Box(false); this.InvokeComponents(s, Boxer.Box(i), result); return(result); }
/// <summary> /// Sets the value of the <see cref="P:DigitalRune.Windows.Controls.TreeViewEx.IsSelectionActive"/> /// attached property to a given <see cref="DependencyObject"/> object. /// </summary> /// <param name="obj">The object on which to set the property value.</param> /// <param name="value">The property value to set.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="obj"/> is <see langword="null"/>. /// </exception> private static void SetIsSelectionActive(DependencyObject obj, bool value) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } obj.SetValue(IsSelectionActivePropertyKey, Boxed.Get(value)); }
/// <summary> /// Sets the value of the <see cref="P:DigitalRune.Windows.Docking.DockTabPanel.IsDraggedProperty"/> attached /// property to a given <see cref="DependencyObject"/> object. /// </summary> /// <param name="obj">The object on which to set the property value.</param> /// <param name="value">The property value to set.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="obj"/> is <see langword="null"/>. /// </exception> public static void SetIsDragged(DependencyObject obj, bool value) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } obj.SetValue(IsDraggedProperty, Boxed.Get(value)); }
/// <summary>Creates an instance of T using m_valueFactory in case its not null or use reflection to create a new T()</summary> /// <returns>An instance of Boxed.</returns> private Boxed CreateValue() { Boxed boxed = null; LazyThreadSafetyMode mode = Mode; if (m_valueFactory != null) { try { // check for recursion if (mode != LazyThreadSafetyMode.PublicationOnly && m_valueFactory == ALREADY_INVOKED_SENTINEL) { throw new InvalidOperationException(); } Func <T> factory = m_valueFactory; if (mode != LazyThreadSafetyMode.PublicationOnly) // only detect recursion on None and ExecutionAndPublication modes { m_valueFactory = ALREADY_INVOKED_SENTINEL; } else if (factory == ALREADY_INVOKED_SENTINEL) { // Another thread raced with us and beat us to successfully invoke the factory. return(null); } boxed = new Boxed(factory()); } catch (Exception ex) { if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode { m_boxed = new LazyInternalExceptionHolder(ex); } throw; } } else { try { boxed = new Boxed((T)Activator.CreateInstance(typeof(T))); } catch (System.MissingMethodException) { Exception ex = new System.MissingMemberException(""); if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode { m_boxed = new LazyInternalExceptionHolder(ex); } throw ex; } } return(boxed); }
/// <summary>Creates an instance of T using m_valueFactory in case its not null or use reflection to create a new T()</summary> /// <returns>An instance of Boxed.</returns> private Boxed CreateValue() { Boxed boxed = null; LazyThreadSafetyMode mode = Mode; if (m_valueFactory != null) { try { // check for recursion if (mode != LazyThreadSafetyMode.PublicationOnly && m_valueFactory == ALREADY_INVOKED_SENTINEL) { throw new InvalidOperationException("Should not try to create the value more than once"); } Func <T> factory = m_valueFactory; if (mode != LazyThreadSafetyMode.PublicationOnly) // only detect recursion on None and ExecutionAndPublication modes { m_valueFactory = ALREADY_INVOKED_SENTINEL; } else if (factory == ALREADY_INVOKED_SENTINEL) { // Another thread raced to successfully invoke the factory. return(null); } boxed = new Boxed(factory()); } catch (Exception ex) { if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode { m_boxed = new LazyInternalExceptionHolder(ex); } throw; } } else { try { boxed = new Boxed((T)Activator.CreateInstance(typeof(T))); } catch (MissingMethodException) { Exception ex = new MissingMemberException(string.Format("The type {0} does not have parameterless constructor", typeof(T).FullName)); if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode { m_boxed = new LazyInternalExceptionHolder(ex); } throw ex; } } return(boxed); }
public void TestBuilderAppliesTransformationsInCorrectOrder() { var startingValue = 20; FluentBuilder <Boxed <int> > builder = new Boxed <int> { Value = startingValue }; builder.AddTransformer(v => v.Value /= 10); builder.AddTransformer(v => v.Value -= 2); builder.Apply().Value.Should().Be(0); }
// waiting wrapper private static IEnumerator Wrapper(IEnumerator coroutine, Boxed <int> counter) { try { yield return(coroutine); } finally { counter.value--; } }
private T Init() { Boxed boxed = null; if (this.boxed == null) { boxed = this.CreateValue(); this.boxed = boxed; } return(boxed.value); }
public override bool TryEnqueue(T res) { while (true) { var q = queue; var @new = Boxed.Of(q.Value.Enqueue(res)); if (Interlocked.CompareExchange(ref queue, @new, q) == q) { return(true); } } }
/// <summary>Creates an instance of T using valueFactory in case its not null or use reflection to create a new T()</summary> /// <returns>An instance of Boxed.</returns> private async Task <Boxed> CreateValue() { Boxed localBoxed = null; LazyThreadSafetyMode mode = Mode; if (valueFactory != null) { try { // check for recursion if (mode != LazyThreadSafetyMode.PublicationOnly && valueFactory == alreadyInvokedSentinel) { throw new InvalidOperationException("Recursive call to Value property"); } Func <Task <T> > factory = valueFactory; if (mode != LazyThreadSafetyMode.PublicationOnly) // only detect recursion on None and ExecutionAndPublication modes { valueFactory = alreadyInvokedSentinel; } else if (factory == alreadyInvokedSentinel) { // Another thread ----d with us and beat us to successfully invoke the factory. return(null); } localBoxed = new Boxed(await factory()); } catch (Exception ex) { if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode { boxed = new LazyInternalExceptionHolder(ex); } throw; } } else { try { localBoxed = new Boxed((T)Activator.CreateInstance(typeof(T))); } catch (MissingMethodException) { Exception ex = new MissingMemberException("Missing parametersless constructor"); if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode { boxed = new LazyInternalExceptionHolder(ex); } throw ex; } } return(localBoxed); }
Vector2 getPointOnFloor(Vector2 inPointOverPointOnFloor) { float theCastingRadius = 0.1f; float theCastingDistance = 100f; Vector2 theCastingDistanceVector = Vector2.down * theCastingDistance; RaycastHit2D[] theHits = Physics2D.CircleCastAll( inPointOverPointOnFloor, theCastingRadius, theCastingDistanceVector); Boxed <RaycastHit2D> theNearestBorderHit = getNearestHitByType <Border>(inPointOverPointOnFloor, theHits, null, true); return(theNearestBorderHit.value.centroid); }
public void Add(TKey key, TElement element) { var boxedKey = new Boxed <TKey>(key); if (_groupings.TryGetValue(boxedKey, out var g)) { g.Add(element); } else { g = new Grouping(key, element); _groupings.Add(boxedKey, g); } }
protected override void Initialize(bool initData) { base.Initialize(initData); if (initData) { _positions = new ObservableCollection <Boxed <int> >(Boxed <int> .ToBoxedItems(_doc.StartPositions)); } if (null != _view) { _view.StartPositions = _positions; } }
private Boxed <T> CreateValue() { Boxed <T> boxed = new Boxed <T> { m_ownerHolder = this.m_holder, Value = (this.m_valueFactory == null) ? default(T) : this.m_valueFactory() }; if ((this.m_holder.Boxed != null) && (this.m_holder.Boxed.m_ownerHolder == this.m_holder)) { throw new InvalidOperationException(Environment.GetResourceString("ThreadLocal_Value_RecursiveCallsToValue")); } this.m_holder.Boxed = boxed; return(boxed); }
// run all coroutines in parallel and wait all to finish public static IEnumerator WaitAll(MonoBehaviour monoBehaviour, params IEnumerator[] coroutines) { var counter = new Boxed <int>(coroutines.Length); foreach (var c in coroutines) { monoBehaviour.StartCoroutine(Wrapper(c, counter)); } while (counter.value > 0) { yield return(null); } }
/// <summary> /// Explicitly loads the linked object /// into the link. /// </summary> public virtual void Load() { if (!_hasLoadedValue) { lock (_lock) { if (!_hasLoadedValue) { _value = new Boxed(CreateValue()); _hasLoadedValue = true; } } } }
/// <summary> /// Private helper function to lazily create the value using the calueSelector if specified in the constructor or the default parameterless constructor /// </summary> /// <returns>Returns the boxed object</returns> private Boxed CreateValue() { Boxed boxed = new Boxed(); boxed.m_ownerHolder = m_holder; boxed.Value = m_valueFactory == null ? default(T) : m_valueFactory(); if (m_holder.Boxed != null && m_holder.Boxed.m_ownerHolder == m_holder) { throw new InvalidOperationException(Environment2.GetResourceString("ThreadLocal_Value_RecursiveCallsToValue")); } m_holder.Boxed = boxed; return(boxed); }
public override bool Apply(bool disposeController) { var resList = new List <int>(Boxed <int> .ToUnboxedItems(_positions)); if (MakeColumnStartListCompliant(resList)) { _positions.Clear(); Boxed <int> .AddRange(_positions, resList); Current.Gui.InfoMessageBox("Start positions were adjusted. Please check the result."); return(false); } _doc.StartPositions = resList.ToArray(); return(ApplyEnd(true, disposeController)); }
/// <summary> /// local helper method to initialize the value /// </summary> /// <returns>The inititialized T value</returns> private TResult LazyInitValue() { Boxed boxed = null; object threadSafeObj = Volatile.Read(ref m_threadSafeObj); bool lockTaken = false; try { if (threadSafeObj != (object)ALREADY_INVOKED_SENTINEL) { Monitor.Enter(threadSafeObj, ref lockTaken); } else { Contract.Assert(m_boxed != null); } if (m_boxed == null) { boxed = CreateValue(); m_boxed = boxed; Volatile.Write(ref m_threadSafeObj, ALREADY_INVOKED_SENTINEL); } else // got the lock but the value is not null anymore, check if it is created by another thread or faulted and throw if so { boxed = m_boxed as Boxed; if (boxed == null) // it is not Boxed, so it is a LazyInternalExceptionHolder { LazyInternalExceptionHolder exHolder = m_boxed as LazyInternalExceptionHolder; Contract.Assert(exHolder != null); exHolder.m_edi.Throw(); } } } finally { if (lockTaken) { Monitor.Exit(threadSafeObj); } } Contract.Assert(boxed != null); return(boxed.m_value); }
public async Task <T> FetchValueAsync() { Boxed boxed = null; if (this.boxed != null) { // Do a quick check up front for the fast path. boxed = this.boxed as Boxed; if (boxed != null) { return(boxed.value); } LazyInternalExceptionHolder exc = this.boxed as LazyInternalExceptionHolder; exc.m_edi.Throw(); } return(await LazyInitValue()); }
private bool TryGetValueOrThrowException(out T value) { Boxed boxed = m_value as Boxed; if (boxed != null) { value = boxed.Value; return(true); } LazyInternalExceptionHolder exHolder = m_value as LazyInternalExceptionHolder; exHolder?.ExceptionInfo.Throw(); value = default(T); return(false); }
public void SetOwner(TextLengthChanger owner) { _totalLegthCorrection = owner.TotalLegthCorrection; }
public TextReplacer(string text) { _workingText = new LazyString(text); TotalLegthCorrection = new Boxed<int>(); }