System.Func.Invoke()

Here are the examples of the csharp api System.Func.Invoke() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

10240 Examples 7

19 View Source File : GameEventData.cs
License : MIT License
Project Creator : 404Lcc

public bool IsCondition()
        {
            return (bool)Condition?.Invoke();
        }

19 View Source File : YoyoAbpWechatTenPayExtensions.cs
License : MIT License
Project Creator : 52ABP

public static IRegisterService UseYoYoSenparcTenpayV3(this IRegisterService registerService, Func<TenPayV3Info> tenPayV3Info, string name, long userId, long tenantId)
        {
            RegisterV3InfoCollection.Register(userId, tenantId, tenPayV3Info().MchId);
            return registerService.RegisterTenpayV3(tenPayV3Info, name);
        }

19 View Source File : Net40.cs
License : MIT License
Project Creator : 2881099

public static Task<TResult> Run<TResult>(Func<TResult> function)
        {
            var tcs = new TaskCompletionSource<TResult>();
            new Thread(() =>
            {
                try
                {
                    tcs.SetResult(function());
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
            })
            { IsBackground = true }.Start();
            return tcs.Task;
        }

19 View Source File : FreeSqlTransaction.cs
License : MIT License
Project Creator : 2881099

public IInsertOrUpdate<T1> InsertOrUpdate<T1>() where T1 : clreplaced
        {
            return _orm.InsertOrUpdate<T1>().WithTransaction(_resolveTran?.Invoke());
        }

19 View Source File : IdleBus`1.ItemInfo.cs
License : MIT License
Project Creator : 2881099

internal TValue GetOrCreate()
            {
                if (isdisposed == true) return null;
                if (value == null)
                {
                    var iscreate = false;
                    var now = DateTime.Now;
                    try
                    {
                        lock (valueLock)
                        {
                            if (isdisposed == true) return null;
                            if (value == null)
                            {
                                value = create();
                                createTime = DateTime.Now;
                                Interlocked.Increment(ref ib._usageQuanreplacedy);
                                iscreate = true;
                            }
                            else
                            {
                                return value;
                            }
                        }
                        if (iscreate)
                        {
                            if (value != null)
                            {
                                if (firstValue == null) firstValue = value; //记录首次值
                                else if (firstValue == value) IsRegisterError = true; //第二次与首次相等,注册姿势错误
                            }
                            ib.OnNotice(new NoticeEventArgs(NoticeType.AutoCreate, key, null, $"{key} 实例+++创建成功,耗时 {DateTime.Now.Subtract(now).TotalMilliseconds}ms,{ib._usageQuanreplacedy}/{ib.Quanreplacedy}"));
                        }
                    }
                    catch (Exception ex)
                    {
                        ib.OnNotice(new NoticeEventArgs(NoticeType.AutoCreate, key, ex, $"{key} 实例+++创建失败:{ex.Message}"));
                        throw;
                    }
                }
                lastActiveTime = DateTime.Now;
                Interlocked.Increment(ref activeCounter);
                return value;
            }

19 View Source File : ExtensionMethods.cs
License : MIT License
Project Creator : 1iveowl

internal static IObservable<T> FinallyAsync<T>(this IObservable<T> source, Func<Task> finalAsync)
        {
            return source
                .Materialize()
                .SelectMany(async n =>
                {
                    switch (n.Kind)
                    {
                        case NotificationKind.OnCompleted:
                            Debug.WriteLine("------ OnCompleted -----");
                            await finalAsync();
                            return n;
                        case NotificationKind.OnError:
                            Debug.WriteLine("------ OnError -----");
                            await finalAsync();
                            return n;
                        case NotificationKind.OnNext:
                            return n;
                        default:throw new NotImplementedException();
                    }
                })
                .Dematerialize();
        }

19 View Source File : Register.cs
License : MIT License
Project Creator : 52ABP

public static void RegisterTenpayV3(UserKeyType userId, TenantKeyType tenantId, Func<TenPayV3Info> tenPayV3Info, string name)
        {
            RegisterV3InfoCollection<UserKeyType, TenantKeyType>.Register(userId, tenantId, tenPayV3Info().MchId);
            TenPayV3InfoCollection.Register(tenPayV3Info(), name);
        }

19 View Source File : BaseDapper.cs
License : MIT License
Project Creator : 1100100

protected TReturn CommandExecute<TReturn>(bool? enableCache, Func<TReturn> execQuery, string sql, object param, string cacheKey, TimeSpan? expire, int? pageIndex = default, int? pageSize = default)
        {
            if (!IsEnableCache(enableCache))
                return execQuery();
            cacheKey = CacheKeyBuilder.Generate(sql, param, cacheKey, pageIndex, pageSize);
            Logger.LogDebug("Get query results from cache.");
            var cache = Cache.TryGet<TReturn>(cacheKey);
            if (cache.ExistKey)
            {
                Logger.LogDebug("Get value from cache successfully.");
                return cache.Value;
            }
            Logger.LogDebug("The cache does not exist, acquire a lock, queue to query data from the database.");
            lock (Lock)
            {
                Logger.LogDebug("The lock has been acquired, try again to get the value from the cache.");
                var cacheResult = Cache.TryGet<TReturn>(cacheKey);
                if (cacheResult.ExistKey)
                {
                    Logger.LogDebug("Try again, get value from cache successfully.");
                    return cacheResult.Value;
                }
                Logger.LogDebug("Try again, still fail to get the value from the cache, start to get the value from the data.");
                var result = execQuery();
                Cache.TrySet(cacheKey, result, expire ?? CacheConfiguration.Expire);
                Logger.LogDebug("Get value from data and write to cache.");
                return result;
            }
        }

19 View Source File : OtherExpressions.cs
License : MIT License
Project Creator : 71

[Fact]
        public void LinkShouldKeepVariableInSync()
        {
            int value = 0;
            LinkedExpression<int> link = X.Link(() => value);

            Func<int> increment = Expression
                .PreIncrementreplacedign(link.Reduce())
                .Compile<Func<int>>();

            increment().ShouldBe(1);
            link.Value.ShouldBe(1);
            value.ShouldBe(1);

            increment().ShouldBe(2);
            link.Value.ShouldBe(2);
            value.ShouldBe(2);
        }

19 View Source File : SqlExtensions.cs
License : MIT License
Project Creator : 1100100

public static string False(this string sql, Func<bool> func)
        {
            return sql.False(func());
        }

19 View Source File : FreeSqlTransaction.cs
License : MIT License
Project Creator : 2881099

public IInsert<T1> Insert<T1>() where T1 : clreplaced
        {
            return _orm.Insert<T1>().WithTransaction(_resolveTran?.Invoke());
        }

19 View Source File : StaticFiles.cs
License : MIT License
Project Creator : 2881099

public static IApplicationBuilder UseFreeAdminLteStaticFiles(this IApplicationBuilder app, string requestPathBase) {
			if (_isStaticFiles == false) {
				lock (_isStaticFilesLock) {
					if (_isStaticFiles == false) {
						var curPath = AppDomain.CurrentDomain.BaseDirectory;
						var zipPath = $"{curPath}/{Guid.NewGuid()}.zip";
						using (var zip = WwwrootStream()) {
							using (var fs = File.Open(zipPath, FileMode.OpenOrCreate)) {
								zip.CopyTo(fs);
								fs.Close();
							}
							zip.Close();
						}
						var wwwrootPath = Path.Combine(curPath, "FreeSql.AdminLTE.wwwroot");
						if (Directory.Exists(wwwrootPath)) Directory.Delete(wwwrootPath, true);
						try {
							System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, wwwrootPath, Encoding.UTF8);
						} catch (Exception ex) {
							throw new Exception($"UseFreeAdminLtePreview 错误,资源文件解压失败:{ex.Message}", ex);
						} finally {
							File.Delete(zipPath);
						}

						app.UseStaticFiles(new StaticFileOptions {
							RequestPath = requestPathBase.TrimEnd('/'),
							FileProvider = new PhysicalFileProvider(wwwrootPath)
						});

						_isStaticFiles = true;
					}
				}
			}

			return app;
		}

19 View Source File : MainWindow_Model.cs
License : MIT License
Project Creator : 1217950746

public async void Execute(object parameter)
        {
            await _asyncExecute();
        }

19 View Source File : AssertHelper.cs
License : MIT License
Project Creator : 39M

[Conditional("UNITY_replacedERTIONS")]
  public static void Implies(string conditionName, bool condition, string resultName, Func<bool> result) {
    if (condition) {
      Implies(conditionName, condition, resultName, result());
    }
  }

19 View Source File : UserLock.cs
License : Apache License 2.0
Project Creator : 0xFireball

public async Task WithExclusiveReadAsync(Func<Task> action)
        {
            await ObtainExclusiveReadAsync();
            await action();
            ReleaseExclusiveRead();
        }

19 View Source File : YoyoAbpAlipayExtension.cs
License : MIT License
Project Creator : 52ABP

public static IServiceCollection AddYoYoAlipay(this IServiceCollection services,
            Func<AlipayOptions> alipayOptionsCreateFunc,
            Action<FTFConfig> ftfConfigCreateAction)
        {
            return services.AddAlipay(options =>
                {
                    options.SetOption(alipayOptionsCreateFunc.Invoke());
                })
                .Configure(ftfConfigCreateAction);
        }

19 View Source File : B2CAuthService.cs
License : MIT License
Project Creator : 1iveowl

private async Task ExecuteSynchronously(Func<Task> task)
        {
            await _semapreplaced.WaitAsync().ConfigureAwait(false);

            try
            {
                await task();
            }
            finally
            {
                _semapreplaced.Release();
            }
        }

19 View Source File : YoyoAbpWechatTenPayExtensions.cs
License : MIT License
Project Creator : 52ABP

public static IRegisterService UseYoYoSenparcTenpayV2(this IRegisterService registerService, Func<TenPayInfo> tenPayInfo, string name, long userId, long tenantId)
        {
            RegisterInfoCollection.Register(userId, tenantId, tenPayInfo().PartnerId);
            return registerService.RegisterTenpayOld(tenPayInfo, name);
        }

19 View Source File : CommandExecuteMonitor.cs
License : MIT License
Project Creator : 1100100

private async Task<TResult> AsyncCommandExecuteMonitor<TResult>(string methodName, string sql, object param, Func<Task<TResult>> func)
        {
            var sw = Stopwatch.StartNew();
            try
            {
                return await func();
            }
            finally
            {
                sw.Stop();
                if (sw.ElapsedMilliseconds > MonitorConfiguration.SlowCriticalValue)
                {
                    SlowCommandNotification(methodName, sql, param, sw.ElapsedMilliseconds);
                }
            }
        }

19 View Source File : OtherExpressions.cs
License : MIT License
Project Creator : 71

[Fact]
        public void ShouldReturnType()
        {
            Expression
                .Lambda<Func<Type>>(X.TypeOf<string>())
                .Compile()()
                .ShouldBe(typeof(string));

            Expression
                .Lambda<Func<Type>>(X.TypeOf(typeof(void)))
                .Compile()()
                .ShouldBe(typeof(void));
        }

19 View Source File : RedisPipeline.cs
License : MIT License
Project Creator : 2881099

public object[] Flush()
        {
            try
            {
                object[] results = new object[0];
                if (_parsers.IsEmpty == false)
                {
                    lock (_bufferLock)
                    {
                        if (_parsers.IsEmpty == false)
                        {
                            _buffer.Position = 0;
                            //Console.WriteLine(Encoding.UTF8.GetString(_buffer.ToArray()));
                            _io.Write(_buffer);
                            
                            _buffer.SetLength(0);

                            results = new object[_parsers.Count];
                        }
                    }
                }

                for (int i = 0; i < results.Length; i++)
                    if (_parsers.TryDequeue(out var func))
                    {
                        try
                        {
                            results[i] = func();
                        }
                        catch(Exception ex)
                        {
                            throw ex;
                        }
                    }

                return results;
            }
            finally
            {
                Active = false;
            }
        }

19 View Source File : IdleBus`1.ItemInfo.cs
License : MIT License
Project Creator : 2881099

internal bool Release(Func<bool> lockInIf)
            {
                lock (valueLock)
                {
                    if (value != null && lockInIf())
                    {
                        value?.Dispose();
                        value = null;
                        Interlocked.Decrement(ref ib._usageQuanreplacedy);
                        Interlocked.Exchange(ref activeCounter, 0);
                        return true;
                    }
                }
                return false;
            }

19 View Source File : CommandExecuteMonitor.cs
License : MIT License
Project Creator : 1100100

private async Task AsyncCommandExecuteMonitor(string methodName, string sql, object param, Func<Task> action)
        {
            var sw = Stopwatch.StartNew();
            try
            {
                await action();
            }
            finally
            {
                sw.Stop();
                if (sw.ElapsedMilliseconds > MonitorConfiguration.SlowCriticalValue)
                {
                    SlowCommandNotification(methodName, sql, param, sw.ElapsedMilliseconds);
                }
            }
        }

19 View Source File : RedisClient.cs
License : MIT License
Project Creator : 2881099

internal protected virtual T LogCall<T>(CommandPacket cmd, Func<T> func)
        {
            cmd.Prefix(Prefix);
            var isnotice = this.Notice != null;
            if (isnotice == false && this.Interceptors.Any() == false) return func();
            Exception exception = null;

            T ret = default(T);
            var isaopval = false;
            IInterceptor[] aops = new IInterceptor[this.Interceptors.Count + (isnotice ? 1 : 0)];
            Stopwatch[] aopsws = new Stopwatch[aops.Length];
            for (var idx = 0; idx < aops.Length; idx++)
            {
                aopsws[idx] = new Stopwatch();
                aopsws[idx].Start();
                aops[idx] = isnotice && idx == aops.Length - 1 ? new NoticeCallInterceptor(this) : this.Interceptors[idx]?.Invoke();
                var args = new InterceptorBeforeEventArgs(this, cmd, typeof(T));
                aops[idx].Before(args);
                if (args.ValueIsChanged && args.Value is T argsValue)
                {
                    isaopval = true;
                    ret = argsValue;
                }
            }
            try
            {
                if (isaopval == false) ret = func();
                return ret;
            }
            catch (Exception ex)
            {
                exception = ex;
                throw;
            }
            finally
            {
                for (var idx = 0; idx < aops.Length; idx++)
                {
                    aopsws[idx].Stop();
                    var args = new InterceptorAfterEventArgs(this, cmd, typeof(T), ret, exception, aopsws[idx].ElapsedMilliseconds);
                    aops[idx].After(args);
                }
            }
        }

19 View Source File : UraganoOptions.cs
License : MIT License
Project Creator : 1100100

public static void SetOption<T>(UraganoOption<T> option, Func<T> func)
        {
            option.Value = func();
        }

19 View Source File : FreeSqlTransaction.cs
License : MIT License
Project Creator : 2881099

public IUpdate<T1> Update<T1>() where T1 : clreplaced
        {
            return _orm.Update<T1>().WithTransaction(_resolveTran?.Invoke());
        }

19 View Source File : FreeSqlTransaction.cs
License : MIT License
Project Creator : 2881099

public ISelect<T1> Select<T1>() where T1 : clreplaced
        {
            return _orm.Select<T1>().WithTransaction(_resolveTran?.Invoke());
        }

19 View Source File : BaseDapper.Async.cs
License : MIT License
Project Creator : 1100100

protected async Task<TReturn> CommandExecuteAsync<TReturn>(bool? enableCache, Func<Task<TReturn>> execQuery, string sql, object param, string cacheKey, TimeSpan? expire, int? pageIndex = default, int? pageSize = default)
        {
            if (!IsEnableCache(enableCache))
                return await execQuery();
            cacheKey = CacheKeyBuilder.Generate(sql, param, cacheKey, pageIndex, pageSize);
            Logger.LogDebug("Get query results from cache.");
            var cache = Cache.TryGet<TReturn>(cacheKey);
            if (cache.ExistKey)
            {
                Logger.LogDebug("Get value from cache successfully.");
                return cache.Value;
            }
            Logger.LogDebug("The cache does not exist, acquire a lock, queue to query data from the database.");
            await SemapreplacedSlim.Value.WaitAsync(TimeSpan.FromSeconds(5));
            try
            {
                Logger.LogDebug("The lock has been acquired, try again to get the value from the cache.");
                var cacheResult = Cache.TryGet<TReturn>(cacheKey);
                if (cacheResult.ExistKey)
                {
                    Logger.LogDebug("Try again, get value from cache successfully.");
                    return cacheResult.Value;
                }
                Logger.LogDebug("Try again, still fail to get the value from the cache, start to get the value from the data.");
                var result = await execQuery();
                Cache.TrySet(cacheKey, result, expire ?? CacheConfiguration.Expire);
                Logger.LogDebug("Get value from data and write to cache.");
                return result;
            }
            finally
            {
                Logger.LogDebug("Release lock.");
                SemapreplacedSlim.Value.Release();
            }
        }

19 View Source File : DbContextAsync.cs
License : MIT License
Project Creator : 2881099

async internal Task ExecCommandAsync() {
			if (isExecCommanding) return;
			if (_actions.Any() == false) return;
			isExecCommanding = true;

			ExecCommandInfo oldinfo = null;
			var states = new List<object>();

			Func<string, Task<int>> dbContextBetch = methodName => {
				if (_dicExecCommandDbContextBetchAsync.TryGetValue(oldinfo.stateType, out var trydic) == false)
					trydic = new Dictionary<string, Func<object, object[], Task<int>>>();
				if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
					var arrType = oldinfo.stateType.MakeArrayType();
					var dbsetType = oldinfo.dbSet.GetType().BaseType;
					var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);

					var returnTarget = Expression.Label(typeof(Task<int>));
					var parm1DbSet = Expression.Parameter(typeof(object));
					var parm2Vals = Expression.Parameter(typeof(object[]));
					var var1Vals = Expression.Variable(arrType);
					tryfunc = Expression.Lambda<Func<object, object[], Task<int>>>(Expression.Block(
						new[] { var1Vals },
						Expression.replacedign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
						Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
						Expression.Label(returnTarget, Expression.Default(typeof(Task<int>)))
					), new[] { parm1DbSet, parm2Vals }).Compile();
					trydic.Add(methodName, tryfunc);
				}
				return tryfunc(oldinfo.dbSet, states.ToArray());
			};
			Func<Task> funcDelete = async () => {
				_affrows += await dbContextBetch("DbContextBetchRemoveAsync");
				states.Clear();
			};
			Func<Task> funcInsert = async  () => {
				_affrows += await dbContextBetch("DbContextBetchAddAsync");
				states.Clear();
			};
			Func<bool, Task> funcUpdate = async (isLiveUpdate) => {
				var affrows = 0;
				if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync");
				else affrows = await dbContextBetch("DbContextBetchUpdateAsync");
				if (affrows == -999) { //最后一个元素已被删除
					states.RemoveAt(states.Count - 1);
					return;
				}
				if (affrows == -998 || affrows == -997) { //没有执行更新
					var laststate = states[states.Count - 1];
					states.Clear();
					if (affrows == -997) states.Add(laststate); //保留最后一个
				}
				if (affrows > 0) {
					_affrows += affrows;
					var islastNotUpdated = states.Count != affrows;
					var laststate = states[states.Count - 1];
					states.Clear();
					if (islastNotUpdated) states.Add(laststate); //保留最后一个
				}
			};

			while (_actions.Any() || states.Any()) {
				var info = _actions.Any() ? _actions.Dequeue() : null;
				if (oldinfo == null) oldinfo = info;
				var isLiveUpdate = false;

				if (_actions.Any() == false && states.Any() ||
					info != null && oldinfo.actionType != info.actionType ||
					info != null && oldinfo.stateType != info.stateType) {

					if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
						//最后一个,合起来发送
						states.Add(info.state);
						info = null;
					}

					switch (oldinfo.actionType) {
						case ExecCommandInfoType.Insert:
							await funcInsert();
							break;
						case ExecCommandInfoType.Delete:
							await funcDelete();
							break;
					}
					isLiveUpdate = true;
				}

				if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
					if (states.Any())
						await funcUpdate(isLiveUpdate);
				}

				if (info != null) {
					states.Add(info.state);
					oldinfo = info;
				}
			}
			isExecCommanding = false;
		}

19 View Source File : UserLock.cs
License : Apache License 2.0
Project Creator : 0xFireball

public async Task WithExclusiveWriteAsync(Func<Task> action)
        {
            await ObtainExclusiveWriteAsync();
            await action();
            ReleaseExclusiveWrite();
        }

19 View Source File : AssertHelper.cs
License : MIT License
Project Creator : 39M

[Conditional("UNITY_replacedERTIONS")]
  public static void Implies(bool condition, Func<bool> result, string message = "") {
    if (condition) {
      Implies(condition, result(), message);
    }
  }

19 View Source File : InterfaceImplementation.cs
License : MIT License
Project Creator : 1996v

public static Type CreateType(Type interfaceType)
        {
            try
            {
                TypeBuilder typeBuilder = Impreplacedembly.DefineInterfaceImpType(interfaceType);

                List<MemberInfo> allMembers = interfaceType.GetAllInterfaceMembers();

                List<MethodInfo> propertyInfos = new List<MethodInfo>();

                foreach (PropertyInfo prop in allMembers.OfType<PropertyInfo>())
                {
                    Type propType = prop.PropertyType;

                    PropertyBuilder propBuilder = typeBuilder.DefineProperty(prop.Name, prop.Attributes, propType, Type.EmptyTypes);

                    MethodInfo iGetter = prop.GetMethod;
                    MethodInfo iSetter = prop.SetMethod;
                    if (iGetter != null)
                    {
                        propertyInfos.Add(iGetter);
                    }

                    if (iSetter != null)
                    {
                        propertyInfos.Add(iSetter);
                    }

                    if (prop.Name == "Item")
                    {
                        if (iGetter != null)
                        {
                            MethodAttributes accessor = iGetter.Attributes;
                            accessor &= ~MethodAttributes.Abstract;
                            MethodBuilder methBuilder = typeBuilder.DefineMethod(iGetter.Name, accessor, iGetter.ReturnType, iGetter.GetParameters().Select(e => e.ParameterType).ToArray());
                            ILGenerator il = methBuilder.GetILGenerator();
                            il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
                            il.Emit(OpCodes.Throw);
                            propBuilder.SetGetMethod(methBuilder);
                        }
                        if (iSetter != null)
                        {
                            MethodAttributes accessor = iSetter.Attributes;
                            accessor &= ~MethodAttributes.Abstract;
                            MethodBuilder methBuilder = typeBuilder.DefineMethod(iSetter.Name, accessor, iSetter.ReturnType, iSetter.GetParameters().Select(e => e.ParameterType).ToArray());
                            ILGenerator il = methBuilder.GetILGenerator();
                            il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
                            il.Emit(OpCodes.Throw);
                            propBuilder.SetSetMethod(methBuilder);
                        }
                        continue;
                    }


                    Func<FieldInfo> getBackingField;
                    {
                        FieldInfo backingField = null;
                        getBackingField =
                            () =>
                            {
                                if (backingField == null)
                                {
                                    backingField = typeBuilder.DefineField("_" + prop.Name + "_" + Guid.NewGuid(), propType, FieldAttributes.Private);
                                }

                                return backingField;
                            };
                    }

                    if (iGetter != null)
                    {
                        MethodAttributes accessor = iGetter.Attributes;
                        accessor &= ~MethodAttributes.Abstract;

                        MethodBuilder methBuilder = typeBuilder.DefineMethod(iGetter.Name, accessor, propType, Type.EmptyTypes);
                        ILGenerator il = methBuilder.GetILGenerator();
                        il.Emit(OpCodes.Ldarg_0);
                        il.Emit(OpCodes.Ldfld, getBackingField());
                        il.Emit(OpCodes.Ret);
                        propBuilder.SetGetMethod(methBuilder);
                    }

                    if (iGetter != null || iSetter != null)
                    {
                        MethodAttributes accessor = iSetter != null ? iSetter.Attributes : MethodAttributes.Private;
                        string name = iSetter != null ? iSetter.Name : "set_" + prop.Name;

                        accessor &= ~MethodAttributes.Abstract;

                        MethodBuilder methBuilder = typeBuilder.DefineMethod(name, accessor, typeof(void), new[] { propType });
                        ILGenerator il = methBuilder.GetILGenerator();

                        if (iGetter != null)
                        {
                            il.Emit(OpCodes.Ldarg_0);
                            il.Emit(OpCodes.Ldarg_1);
                            il.Emit(OpCodes.Stfld, getBackingField());
                            il.Emit(OpCodes.Ret);
                        }
                        else
                        {
                            il.Emit(OpCodes.Ret);
                        }

                        propBuilder.SetSetMethod(methBuilder);
                    }
                }

                foreach (MethodInfo method in allMembers.OfType<MethodInfo>().Except(propertyInfos))
                {
                    MethodBuilder methBuilder = typeBuilder.DefineMethod(method.Name, MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final, method.ReturnType, method.GetParameters().Select(e => e.ParameterType).ToArray());
                    if (method.IsGenericMethod)
                    {
                        methBuilder.DefineGenericParameters(method.GetGenericArguments().Select(e => e.Name).ToArray());
                    }
                    ILGenerator il = methBuilder.GetILGenerator();
                    il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
                    il.Emit(OpCodes.Throw);

                    typeBuilder.DefineMethodOverride(methBuilder, method);
                }

                return typeBuilder.CreateTypeInfo();
            }
            catch
            {
                throw BssomSerializationTypeFormatterException.UnsupportedType(interfaceType);
            }
        }

19 View Source File : CustomEditorBase.cs
License : MIT License
Project Creator : 39M

public override void OnInspectorGUI() {
      _modifiedProperties.Clear();
      SerializedProperty iterator = serializedObject.Gereplacederator();
      bool isFirst = true;

      while (iterator.NextVisible(isFirst)) {
        List<Func<bool>> conditionalList;
        if (_conditionalProperties.TryGetValue(iterator.name, out conditionalList)) {
          bool allTrue = true;
          for (int i = 0; i < conditionalList.Count; i++) {
            allTrue &= conditionalList[i]();
          }
          if (!allTrue) {
            continue;
          }
        }

        Action<SerializedProperty> customDrawer;

        List<Action<SerializedProperty>> decoratorList;
        if (_specifiedDecorators.TryGetValue(iterator.name, out decoratorList)) {
          for (int i = 0; i < decoratorList.Count; i++) {
            decoratorList[i](iterator);
          }
        }

        EditorGUI.BeginChangeCheck();

        if (_specifiedDrawers.TryGetValue(iterator.name, out customDrawer)) {
          customDrawer(iterator);
        } else {
          using (new EditorGUI.DisabledGroupScope(isFirst)) {
            EditorGUILayout.PropertyField(iterator, true);
          }
        }

        if (EditorGUI.EndChangeCheck()) {
          _modifiedProperties.Add(iterator.Copy());
        }

        isFirst = false;
      }

      serializedObject.ApplyModifiedProperties();
    }

19 View Source File : CommandExecuteMonitor.cs
License : MIT License
Project Creator : 1100100

private TResult SyncCommandExecuteMonitor<TResult>(string methodName, string sql, object param, Func<TResult> func)
        {
            var sw = Stopwatch.StartNew();
            try
            {
                return func();
            }
            finally
            {
                sw.Stop();
                if (sw.ElapsedMilliseconds > MonitorConfiguration.SlowCriticalValue)
                {
                    SlowCommandNotification(methodName, sql, param, sw.ElapsedMilliseconds);
                }
            }
        }

19 View Source File : NoDuplicationFuzzersShould.cs
License : Apache License 2.0
Project Creator : 42skillz

private static void CheckThatNoDuplicationIsMadeWhileGenerating<T>(IFuzz fuzzer, long maxNumberOfElements, Func<T> fuzzingFunction)
        {
            var returnedElements = new HashSet<T>(); //T
            for (var i = 0; i < maxNumberOfElements; i++)
            {
                try
                {
                    var element = fuzzingFunction();
                    returnedElements.Add(element);
                    //TestContext.WriteLine(element.ToString());
                }
                catch (DuplicationException) { }
            }

            Check.WithCustomMessage("The fuzzer was not able to generate the maximum number of expected entries")
                .That(returnedElements).Hreplacedize(maxNumberOfElements);
        }

19 View Source File : B2CAuthService.cs
License : MIT License
Project Creator : 1iveowl

private async Task<T> ExecuteSynchronously<T>(Func<Task<T>> task)
        {
            await _semapreplaced.WaitAsync().ConfigureAwait(false);

            try
            {
                return await task();
            }
            finally
            {
                _semapreplaced.Release();
            }

        }

19 View Source File : Register.cs
License : MIT License
Project Creator : 52ABP

public static void RegisterTenpayOld(UserKeyType userId, TenantKeyType tenantId, Func<TenPayInfo> tenPayInfo, string name)
        {
            RegisterInfoCollection<UserKeyType, TenantKeyType>.Register(userId, tenantId, tenPayInfo().PartnerId);
            TenPayInfoCollection.Register(tenPayInfo(), name);
        }

19 View Source File : UserLock.cs
License : Apache License 2.0
Project Creator : 0xFireball

public async Task WithConcurrentReadAsync(Func<Task> action)
        {
            await ObtainConcurrentReadAsync();
            await action();
            ReleaseConcurrentRead();
        }

19 View Source File : YoyoAbpWechatTenPayExtensions.cs
License : MIT License
Project Creator : 52ABP

public static IRegisterService UseYoYoSenparcTenpayV2<UserKeyType, TenantKeyType>(this IRegisterService registerService, Func<TenPayInfo> tenPayInfo, string name, UserKeyType userId = default(UserKeyType), TenantKeyType tenantId = default(TenantKeyType))
        {
            RegisterInfoCollection<UserKeyType, TenantKeyType>.Register(userId, tenantId, tenPayInfo().PartnerId);
            return registerService.RegisterTenpayOld(tenPayInfo, name);
        }

19 View Source File : QuickAndDirtyCache.cs
License : MIT License
Project Creator : 1iveowl

public async Task<T> TryGetFromCache<T>(
            string key, 
            Func<Task<T>> renewObjectFunc,
            Func<T, Task<bool>> isCachedObjectValidFunc)
        {
            if (_cacheDictionary.TryGetValue(key, out var cachedObj))
            {
                var obj = (T) cachedObj;

                if (await isCachedObjectValidFunc(obj))
                {
                    return obj;
                }
            }

            var newObj = await renewObjectFunc();

            await CacheObject(newObj, key);

            return newObj;

        }

19 View Source File : YoyoAbpWechatTenPayExtensions.cs
License : MIT License
Project Creator : 52ABP

public static IRegisterService UseYoYoSenparcTenpayV3<UserKeyType, TenantKeyType>(this IRegisterService registerService, Func<TenPayV3Info> tenPayV3Info, string name, UserKeyType userId = default(UserKeyType), TenantKeyType tenantId = default(TenantKeyType))
        {
            RegisterV3InfoCollection<UserKeyType, TenantKeyType>.Register(userId, tenantId, tenPayV3Info().MchId);
            return registerService.RegisterTenpayV3(tenPayV3Info, name);
        }

19 View Source File : ResourceThrottle.cs
License : Apache License 2.0
Project Creator : 0xFireball

public async Task WithResourceAsync(Func<Task> action)
        {
            await AcquireAsync();
            await action();
            Release();
        }

19 View Source File : Beacon.cs
License : MIT License
Project Creator : 5argon

private static IEnumerator SpamInternal<T>(T beacon, BeaconConstraint bc, Func<IEnumerator> spamAction, bool lookFor) where T : Enum
        {
            while (Beacon.Check(beacon, bc) == lookFor)
            {
                if (spamAction != null)
                {
                    yield return spamAction();
                }
                else
                {
                    yield return null;
                }
            }
        }

19 View Source File : DefaultPolicy.cs
License : MIT License
Project Creator : 2881099

public T OnCreate()
        {
            return CreateObject();
        }

19 View Source File : SqlExtensions.cs
License : MIT License
Project Creator : 1100100

public static string True(this string sql, Func<bool> func)
        {
            return sql.True(func());
        }

19 View Source File : ScenarioContext.cs
License : MIT License
Project Creator : 0x1000000

public ISqDatabase CreteConnection()
        {
            return this._dbFactory();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 0xd4d

static void Disreplacedemble(DisasmJobContext context, DisasmJob job) {
			var (writer, disposeWriter) = job.GetTextWriter();
			try {
				var methods = job.Methods;
				Array.Sort(methods, SortMethods);
				for (int i = 0; i < methods.Length; i++) {
					if (i > 0)
						writer.WriteLine();

					var method = methods[i];
					context.Disreplacedembler.Disreplacedemble(context.Formatter, writer, method);
				}
			}
			finally {
				if (disposeWriter)
					writer.Dispose();
			}
		}

19 View Source File : SqlExtensions.cs
License : MIT License
Project Creator : 1100100

public static string Splice(this string sql, params Func<bool>[] conditions)
        {
            return sql.Splice(conditions.Select(p => p()).ToArray());
        }

19 View Source File : TimeExtensions.cs
License : MIT License
Project Creator : 1100100

public static long CurrentTimeMillis()
        {
            return currentTimeFunc();
        }

19 View Source File : FreeSqlTransaction.cs
License : MIT License
Project Creator : 2881099

public IDelete<T1> Delete<T1>() where T1 : clreplaced
        {
            return _orm.Delete<T1>().WithTransaction(_resolveTran?.Invoke());
        }

See More Examples