public static int CallDel(lua_State L, int start, Delegate del) { RefAction a = (RefAction)del; a(); return(0); }
public PostEventWrapper(RefAction <T> _call, T _prm, uint _delayFrame = 1u) { this.prm = _prm; this.frameNum = Singleton <FrameSynchr> .get_instance().CurFrameNum + _delayFrame; this.callback = _call; }
public void RmvEventHandler <ParamType>(GameEventDef evt, RefAction <ParamType> handler) { if (this.CheckValidRmv(evt, handler)) { this.ActionTable[(int)evt] = (RefAction <ParamType>)Delegate.Remove((RefAction <ParamType>) this.ActionTable[(int)evt], handler); } }
public static void Foreach <T>(this T[,] array, RefAction <T> f) { foreach (var(y, x) in array.Indexes()) { f(ref array[y, x]); } }
static RefAction <object, object> ToOpenActionDelegate <T, TParam>(System.Reflection.MethodInfo methodInfo) { // Convert the slow MethodInfo into a fast, strongly typed, open delegate Type objectType = typeof(T); Type parameterType = typeof(TParam); RefAction <object, object> ret; if (objectType.IsValueType) { RefAction <T, TParam> propertySetter = (RefAction <T, TParam>)Delegate.CreateDelegate(typeof(RefAction <T, TParam>), null, methodInfo); // we are trying to set some struct internal value. ret = (ref object target, object param) => { T boxed = (T)target; propertySetter(ref boxed, (TParam)System.Convert.ChangeType(param, parameterType)); target = boxed; }; } else { Action <T, TParam> action = (Action <T, TParam>)Delegate.CreateDelegate(typeof(Action <T, TParam>), null, methodInfo); ret = (ref object target, object param) => action((T)target, (TParam)System.Convert.ChangeType(param, parameterType)); } return(ret); }
public static void Main(string[] args) { var s = new S(); var mi = s.GetType().GetMethod("set_Value"); /* * var deleg = (RefAction<S, string>)Delegate.CreateDelegate(typeof(RefAction<S, string>), null, mi); * * deleg(ref s, "hello"); * * RefAction<object, object> deleg2 = (ref object target, object param) => { * S boxed = (S)target; * deleg(ref boxed, (string)param); * target = boxed; * }; */ RefAction <object, object> deleg2 = ToOpenActionDelegate <S, string>(mi); var o = (object)s; deleg2(ref o, "world"); s = (S)o; Console.WriteLine(s.Value); //prints "world" Console.ReadKey(true); }
public bool DoWork(RefAction work, string threadname, int timeout = -1) { try { if (resourceLock.TryEnterWriteLock(timeout)) { if (work != null) { work(); } } else { Console.WriteLine("Lock time out on thread {0}", threadname); } } finally { Console.WriteLine("{0} releasing resource", threadname); if (resourceLock.IsWriteLockHeld) { resourceLock.ExitWriteLock(); } } return(false); }
// METHODS public override void PerformStep() { // do move for last point direction(ref points[points.Length - 1]); // copy path for (int i = 0; i < points.Length - 1; ++i) { points[i].Y = points[i + 1].Y; } // calc steps and change direction ++stepsDone; if (stepsDone == stepsLengthConfig[stepIndex]) { SwitchDirection(); ++stepIndex; stepsDone = 0; // if cicle is done... if (stepIndex == stepsLengthConfig.Length) { // ... repeat it direction = StraightForward; stepIndex = 0; } } }
public void SendEvent<ParamType>(GameEventDef evt, ref ParamType prm) { RefAction<ParamType> refAction = this.ActionTable[(int)evt] as RefAction<ParamType>; if (refAction != null) { refAction(ref prm); } }
public Action UseSection <TSection>(RefAction <TSection> action, Action fallback) { return(action switch { RefAction <Health> use => () => use(ref this.health), RefAction <Resistance> use => () => use(ref this.resistanceMB.resistance), RefAction <EffectRunnerMB> use => () => use(ref this.effectRunnerMB), _ => fallback, });
internal UdpServer(IPEndPoint address, int backlog, MemoryAllocator <byte> allocator, Func <int, IExchangePool> exchangePoolFactory, ILoggerFactory loggerFactory) : base(address, backlog, allocator, loggerFactory) { channels = new INetworkTransport.ChannelPool <Channel>(backlog); cancellationHandler = channels.CancellationRequested; cancellationInvoker = Channel.Cancel; exchanges = exchangePoolFactory(backlog); }
/// <summary> /// Applies specific action to each array element. /// </summary> /// <remarks> /// This method support modification of array elements /// because each array element is passed by reference into action. /// </remarks> /// <typeparam name="T">Type of array elements.</typeparam> /// <param name="array">An array to iterate.</param> /// <param name="action">An action to be applied for each element.</param> public static void ForEach <T>(this T[] array, RefAction <T, long> action) { // TODO: Change long to nint in RefAction signature in .NET 6 for (var i = 0L; i < array.LongLength; i++) { action(ref array[i], i); } }
/// <summary> /// Creates a new <see cref="ObjectPool{T}"/> instance. /// </summary> /// <param name="collectThreshold">Threshold when calling <see cref="Collect"/>.</param> /// <param name="alloc">Allocation function.</param> /// <param name="dealloc">Deallocation function.</param> /// <param name="reset">Object reset function.</param> internal ObjectPool(int collectThreshold, [NotNull] Func <T> alloc, [NotNull] Action <T> dealloc, [CanBeNull] RefAction <T> reset) { _objectsInUse = new HashSet <T>(); _freeObjects = new LinkedList <T>(); _collectThreshold = collectThreshold; _alloc = alloc; _dealloc = dealloc; _reset = reset; }
public void PostEvent<ParamType>(GameEventDef evt, ref ParamType prm) { RefAction<ParamType> refAction = this.ActionTable[(int)evt] as RefAction<ParamType>; if (refAction != null) { PostEventWrapper<ParamType> postEventWrapper = new PostEventWrapper<ParamType>(refAction, prm, 1u); this.postEventList.Add(postEventWrapper); } }
protected async Task DatabaseConfigurations(SetupFunc setupConfigurationFunc, string debug, string raftRequestId, RefAction beforeSetupConfiguration = null, Action <DynamicJsonValue, BlittableJsonReaderObject, long> fillJson = null, HttpStatusCode statusCode = HttpStatusCode.OK) { if (TryGetAllowedDbs(Database.Name, out var _, requireAdmin: true) == false) { return; } if (ResourceNameValidator.IsValidResourceName(Database.Name, ServerStore.Configuration.Core.DataDirectory.FullPath, out string errorMessage) == false) { throw new BadRequestException(errorMessage); } ServerStore.EnsureNotPassive(); using (ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context)) { var configurationJson = await context.ReadForMemoryAsync(RequestBodyStream(), debug); beforeSetupConfiguration?.Invoke(Database.Name, ref configurationJson, context); var(index, _) = await setupConfigurationFunc(context, Database.Name, configurationJson, raftRequestId); DatabaseTopology dbTopology; using (context.OpenReadTransaction()) { dbTopology = ServerStore.Cluster.ReadDatabaseTopology(context, Database.Name); } if (dbTopology.RelevantFor(ServerStore.NodeTag)) { var db = await ServerStore.DatabasesLandlord.TryGetOrCreateResourceStore(Database.Name); await db.RachisLogIndexNotifications.WaitForIndexNotification(index, ServerStore.Engine.OperationTimeout); } else { await ServerStore.Cluster.WaitForIndexNotification(index); } HttpContext.Response.StatusCode = (int)statusCode; using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream())) { var json = new DynamicJsonValue { ["RaftCommandIndex"] = index, }; fillJson?.Invoke(json, configurationJson, index); context.Write(writer, json); writer.Flush(); } } }
private void SwitchDirection() { if (direction == Down) { direction = Up; } else { direction = Down; } }
internal UdpClient(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, int backlog, MemoryAllocator <byte> allocator, Func <long> appIdGenerator, ILoggerFactory loggerFactory) : base(remoteEndPoint, backlog, allocator, loggerFactory) { channels = new INetworkTransport.ChannelPool <Channel>(backlog); cancellationHandler = channels.CancellationRequested; applicationId = appIdGenerator(); streamNumber = long.MinValue; cancellationInvoker = channels.CancellationRequested; this.localEndPoint = localEndPoint; }
protected override void ResetImage() { stepsDone = 0; stepIndex = 0; direction = StraightForward; points = new Point[width * 2]; for (int i = 0; i < points.Length; ++i) { points[i] = new Point(i / 4, height / 2); } }
public static void Check <T>(RefAction <T> action, ref T arg) { try { action.Invoke(ref arg); } finally { WriteDebug(action, arg); ThrowIfError(action); } }
public static void ForEach <T>(this T[] array, RefAction <T> action) { if (action == null) { throw new ArgumentNullException(nameof(action)); } for (int i = 0; i < array.Length; i++) { action?.Invoke(ref array[i]); } }
public void ForEach(RefAction <T> action) { if (action == null) { throw new ArgumentNullException("action"); } for (int i = 0; i < size; i++) { action(ref items[i]); } }
/// <summary> /// Executes an action for each item in the collection and passes to the action /// the handle of the element /// </summary> /// <param name="action">Action to execute</param> public void ForEachWithHandle(RefAction <T, int> action) { int count = this.RawCount; for (int i = 0; i < count; ++i) { if (this.UsedList[i] == 1) { action(ref Items[i], i); } } }
/// <summary> /// Executes an action for each item in the collection /// Note: Internally uses a for loop. /// </summary> /// <param name="action">Action to execute, passed by reference</param> public void ForEach(RefAction <T> action) { int count = this.RawCount; for (int i = 0; i < count; ++i) { if (this.UsedList[i] == 1) { action(ref Items[i]); } } }
public static int Call(lua_State L) { try { RefAction a = ToLightObject <RefAction>(L, lua_upvalueindex(1), false); a(); return(0); } catch (Exception e) { return(luaL_error(L, e.Message)); } }
/// <summary> /// refを使用した構造体への作用の反映 /// </summary> public static void ForEach <T>(this IList <T> list, RefAction <T> action) { if (action == null) { throw new ArgumentNullException(nameof(action)); } for (int i = 0; i < list.Count; ++i) { var item = list[i]; action?.Invoke(ref item); list[i] = item; } }
protected async Task DatabaseConfigurations(SetupFunc setupConfigurationFunc, string debug, string raftRequestId, RefAction beforeSetupConfiguration = null, Action <DynamicJsonValue, BlittableJsonReaderObject, long> fillJson = null, HttpStatusCode statusCode = HttpStatusCode.OK) { if (TryGetAllowedDbs(Database.Name, out var _, requireAdmin: true) == false) { return; } if (ResourceNameValidator.IsValidResourceName(Database.Name, ServerStore.Configuration.Core.DataDirectory.FullPath, out string errorMessage) == false) { throw new BadRequestException(errorMessage); } await ServerStore.EnsureNotPassiveAsync(); using (ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context)) { var configurationJson = await context.ReadForMemoryAsync(RequestBodyStream(), debug); beforeSetupConfiguration?.Invoke(Database.Name, ref configurationJson, context); var(index, _) = await setupConfigurationFunc(context, Database.Name, configurationJson, raftRequestId); await WaitForIndexToBeApplied(context, index); HttpContext.Response.StatusCode = (int)statusCode; using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream())) { var json = new DynamicJsonValue { ["RaftCommandIndex"] = index, }; fillJson?.Invoke(json, configurationJson, index); context.Write(writer, json); writer.Flush(); } } }
/// <summary> /// Allocates a structure of a given unmanaged type on the stack, with a specified alignment. /// </summary> /// <typeparam name="T">The type parameter of the structure to allocate and aligned on the stack.</typeparam> /// <param name="alignment">The alignment of the structure.</param> /// <param name="action">The callback where the aligned structure is passed.</param> /// <remarks>The structure can only be used in the callback. Any usage of it outside of that scope manipulate a freed memory.</remarks> public static unsafe void Allocate <T>(int alignment, RefAction <T> action) where T : unmanaged { // The worst case is that the alignment is only possible after the alignment value itself var memoryToAllocate = alignment + sizeof(T) - 1; // Allocate the memory on the stack var memory = stackalloc byte[memoryToAllocate]; // Determine the offset between the allocated address and the aligned address var offset = (long)memory & alignment - 1; // If there is an offset, relocate the pointer to the aligned address if (offset != 0) { memory += alignment - offset; } // Perform some black magic pointer manipulations.. // No just kidding, reinterpret the aligned memory address as the structure, // the ref keywords are here to prevent the structure ot be copied, as a structure // assignment is equal to a copy in C#. ref var s = ref *(T *)memory;
public IEnumerator Clear() { var health = new Health(); var sheet = new MockSheet { useSection = (d, fb) => d switch { RefAction <Health> u => () => u(ref health), _ => fb, } }; var inspect = new GameObject("inspector").AddComponent <MockUISheetInspectMB>(); var uIHealth = new GameObject("health").AddComponent <MockUIInspectHealth>(); inspect.uIHealth = uIHealth; yield return(new WaitForEndOfFrame()); inspect.SetSheet(sheet); inspect.Clear(); inspect.Monitor(); health.hp = 42f; Assert.AreEqual(0f, uIHealth.hp); }
static void Main(string[] args) { RefAction <StringBuilder> action1 = (ref StringBuilder sb) => { Console.WriteLine(sb); sb = new StringBuilder("x"); }; RefAction <StringBuilder> action2 = (ref StringBuilder sb) => { Console.WriteLine(sb); sb.Append("y"); }; RefAction <StringBuilder> action3 = (ref StringBuilder sb) => { Console.WriteLine(sb); sb.Append("z"); }; RefAction <StringBuilder> all = action1 + action2 + action3; StringBuilder builder = new StringBuilder("a"); all(ref builder); Console.WriteLine(builder); }
static public void 多功能处理(Bitmap 位图, string 功能, RefAction <byte, byte, byte> 处理方法) { BitmapData 位图数据 = 位图.LockBits(new Rectangle(0, 0, 位图.Width, 位图.Height), ImageLockMode.ReadWrite, 位图.PixelFormat); byte 字节数 = 3; if (位图.PixelFormat == PixelFormat.Format32bppArgb) { 字节数 = 4; //为了适应24位图和32位图这两种情况 } Random 随机 = new (); 随机种子 = (uint)随机.Next(int.MaxValue); unsafe { byte *位针 = (byte *)(位图数据.Scan0); for (int y = 0; y < 位图数据.Height; y++, 位针 += 位图数据.Stride - 位图数据.Width * 字节数) { for (int x = 0; x < 位图数据.Width; x++, 位针 += 字节数) { 处理方法(ref 位针[红], ref 位针[绿], ref 位针[蓝]); //把代码展开写在这里速度最快,调用函数会慢一点,用委托调用又会更慢一点.这样写代码简洁了,但速度慢了些 } } } 位图.UnlockBits(位图数据); }