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 Source : OtherExpressions.cs
with MIT License
from 71

[Fact]
        public void LinkShouldKeepValueInSync()
        {
            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(0);

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

19 Source : CompilationProcessor.cs
with MIT License
from 71

public bool TryInitialize(CSharpCompilation compilation, CancellationToken cancellationToken)
        {
            if (IsInitialized && IsInitializationSuccessful)
                return true;

            List<CompilationEditor> editors = Editors;
            var addDiagnostic = AddDiagnostic;
            CSharpCompilation clone = compilation.Clone();

            IsInitialized = true;

            // Log all previously encountered exceptions
            initializationExceptions.Capacity = initializationExceptions.Count;

            var exceptions = initializationExceptions.MoveToImmutable();

            for (int i = 0; i < exceptions.Length; i++)
            {
                var (exception, data) = exceptions[i];
                var location = data.ApplicationSyntaxReference.ToLocation();

                addDiagnostic(Diagnostic.Create(InitializationError, location, data.AttributeClreplaced, exception.Message.Filter(), exception.StackTrace.Filter()));
            }

            if (exceptions.Length > 0)
                return false;

            // Initialize all editors
            int editorsCount = editors.Count;

            for (int i = 0; i < editorsCount; i++)
            {
                CompilationEditor editor = editors[i];

                try
                {
                    // Register
                    if (!editor.TryRegister(this, addDiagnostic, clone, cancellationToken, out var children, out var exception))
                    {
                        addDiagnostic(Diagnostic.Create(EditorError, Location.None, editor.ToString(), exception.ToString()));
                        return false;
                    }

                    // Make sure no error was diagnosed by the editor
                    if (GetDiagnostics().Any(x => x.Severity == DiagnosticSeverity.Error))
                    {
                        return false;
                    }

                    // Optionally register some children
                    if (children == null || children.Length == 0)
                        continue;

                    editors.Capacity += children.Length;

                    for (int j = 0; j < children.Length; j++)
                    {
                        CompilationEditor child = children[j];

                        if (child == null)
                        {
                            addDiagnostic(Diagnostic.Create(
                                id: "MissingChild", category: Common.DiagnosticsCategory,
                                message: $"A child returned by the '{editor}' editor is null.",
                                severity: DiagnosticSeverity.Warning, defaultSeverity: DiagnosticSeverity.Warning,
                                isEnabledByDefault: true, warningLevel: 1, isSuppressed: false));

                            continue;
                        }

                        editors.Insert(i + j + 1, child);
                        editorsCount++;
                    }
                    // Since we insert them right after this one, the for loop will take care of initializing them easily
                    // => No recursion, baby
                }
                catch (Exception e)
                {
                    while (e is TargetInvocationException tie)
                        e = tie.InnerException;

                    addDiagnostic(Diagnostic.Create(EditorError, Location.None, editor.ToString(), e.Message.Filter()));

                    return false;
                }
            }

            // We got this far: the initialization is a success.
            IsInitializationSuccessful = true;
            return true;
        }

19 Source : Store.cs
with MIT License
from 71

public T GetOrAdd<T>(object key, Func<T> value)
        {
            var keys = Keys.UnderlyingArray;

            for (int i = 0; i < keys.Length; i++)
            {
                if (!ReferenceEquals(keys[i], key))
                    continue;

                object obj = Values[i];

                if (obj is T t)
                    return t;

                throw new InvalidCastException();
            }

            T val = value();

            Keys.Add(key);
            Values.Add(val);

            return val;
        }

19 Source : ObjectPool.Pool.partial.cs
with MIT License
from 7Bytes-Studio

public override ObjectBase Spawn(Type objectType, Predicate<ObjectBase> predicate = null,Func<object> factoryArgsCallback=null)
            {
                CheckObjectTypeOrThrow(objectType);
                var target = null != predicate? FindTypeInPool(predicate):FindTypeInPool(objectType);
                if (null != target && !target.Lock)
                {
                    lock (m_Lock)
                    {
                        m_LinkedListObject_InPool.Remove(target);
                        m_LinkedListObject_OutPool.AddLast(target);
                    }
                    target.Spawn();
                    return target;
                }
                else
                {
                    CheckCapacityOrThrow();
                    ObjectBase ins = null;
                    var callback =  PoolFactory.GetBinding(objectType);
                    if (null != callback)
                    {
                        ins = callback.Invoke();
                    }
                    else
                    {
                        //throw new Exception(string.Format("没有获取到类型'{0}'的委托绑定!",objectType));
                        ins = Utility.Reflection.New(objectType) as ObjectBase;
                    }

                    lock (m_Lock)
                    {
                        m_LinkedListObject_OutPool.AddLast(ins);
                    }
                    
                    ins.SetPoolOwnersName(Name);
                    if (null != factoryArgsCallback)
                    {
                        ins.Spawn(factoryArgsCallback.Invoke());
                    }
                    else
                    {
                        ins.Spawn();
                    }
                    return ins;
                }
            }

19 Source : RedisCache.cs
with Apache License 2.0
from 91270

public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
        {
            if (ContainsKey<V>(cacheKey))
            {
                return Get<V>(cacheKey);
            }
            else
            {
                var result = create();
                Add(cacheKey, result, cacheDurationInSeconds);
                return result;
            }
        }

19 Source : JobBase.cs
with Apache License 2.0
from 91270

public async Task<string> ExecuteJob(IJobExecutionContext context, Func<Task> job)
        {
            string jobHistory = $"Run Job [Id:{context.JobDetail.Key.Name},Group:{context.JobDetail.Key.Group}]";

            try
            {
                var s = context.Trigger.Key.Name;
                //记录Job时间
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                //执行任务
                await job();
                stopwatch.Stop();
                jobHistory += $", Succeed , Elapsed:{stopwatch.Elapsed.TotalMilliseconds} ms";
            }
            catch (Exception ex)
            {
                JobExecutionException e2 = new JobExecutionException(ex);
                //true  是立即重新执行任务 
                e2.RefireImmediately = true;
                jobHistory += $", Fail ,Exception:{ex.Message}";
            }

            return jobHistory;
        }

19 Source : BaseHub.cs
with GNU Lesser General Public License v3.0
from 8720826

protected async Task<bool> DoCommand(Func<Task> func)
        {
            //踢出自己
            var connectionId = await _mudOnlineProvider.GetConnectionId(_account.PlayerId);
            if (string.IsNullOrEmpty(connectionId))
            {
                await KickOut(Context.ConnectionId);
                await ShowSystemMessage(Context.ConnectionId, "你已经断线,请刷新或重新登录");
                Context.Abort();
                return await Task.FromResult(false);
            }

            if (connectionId != Context.ConnectionId)
            {
                await KickOut(Context.ConnectionId);
                await ShowSystemMessage(Context.ConnectionId, "你已经断线,请刷新或重新登录");
                Context.Abort();
                return await Task.FromResult(false);
            }

            await func?.Invoke();


            if (!IsValidOperation())
            {
                foreach (var notification in _notifications.GetNotifications())
                {
                    await ShowSystemMessage(Context.ConnectionId, notification.Content);
                }
                return await Task.FromResult(false);
            }
            return await Task.FromResult(true);
        }

19 Source : TestUnlimitedBuffer.cs
with MIT License
from a1q123456

[TestMethod]
        public void TestAsyncWriteAndRead()
        {
            var buffer = new ByteBuffer(512, 35767);
            short c = 0;
            Func<Task> th1 = async () =>
            {
                byte i = 0;
                while (c < short.MaxValue)
                {
                    var arr = new byte[new Random().Next(256, 512)];
                    for (var j = 0; j < arr.Length; j++)
                    {
                        arr[j] = i;
                        i++;

                        if (i > 100)
                        {
                            i = 0;
                        }
                    }
                    await buffer.WriteToBufferAsync(arr);
                    c++;
                }
            };

            Func<Task> th2 = async () =>
            {
                while (c < short.MaxValue)
                {
                    var arr = new byte[new Random().Next(129, 136)];
                    if (buffer.Length >= arr.Length)
                    {
                        await buffer.TakeOutMemoryAsync(arr);

                        for (int i = 1; i < arr.Length; i++)
                        {
                            replacedert.IsTrue(arr[i] - arr[i - 1] == 1 || arr[i - 1] - arr[i] == 100);
                        }
                    }
                }
            };

            var t = th1();
            th2();
            t.Wait();
        }

19 Source : FsmUtil.cs
with GNU General Public License v3.0
from a2659802

private IEnumerator Coroutine()
        {
            yield return _coro?.Invoke();
            Finish();
        }

19 Source : ThingEntry.cs
with Apache License 2.0
from AantCoder

public bool SetFaction(string fractionColonist, Func<string> fractionRoyalty)
        {
            if (string.IsNullOrEmpty(Data) || !Data.Contains(" Clreplaced=\"Pawn\"")) return false;
            if (MainHelper.DebugMode) File.WriteAllText(Loger.PathLog + "MailPawnB" + (++nnnn).ToString() + ".xml", Data);

            //логика коррекции основывается на 3х группыах:
            //колонист, человек не колонист (пират или пленник), животное

            bool col = Data.Contains("<kindDef>Colonist</kindDef>");
            if (!col) col = Data.Contains("ColonistGeneral</kindDef>"); //для мода с андроидами

            bool isAnimal = GameXMLUtils.GetByTag(Data, "def") == GameXMLUtils.GetByTag(Data, "kindDef");

            //для всех людей устанавливаем фракцию игрока (у животных не меняем)

            if (!isAnimal)
            {
                string fraction = fractionColonist; //col ? fractionColonist : fractionPirate;
                Data = GameXMLUtils.ReplaceByTag(Data, "faction", fraction);
                if (!col) Data = GameXMLUtils.ReplaceByTag(Data, "kindDef", "Colonist"); //"Pirate"
                //if (MainHelper.DebugMode) Loger.Log(" Replace faction=>" + fraction);
            }

            //если это гости, то убираем у них это свойство - оно должно выставиться потом

            Data = GameXMLUtils.ReplaceByTag(Data, "guest", @"
    <hostFaction>null</hostFaction>
    <interactionMode>NoInteraction</interactionMode>
    <spotToWaitInsteadOfEscaping>(-1000, -1000, -1000)</spotToWaitInsteadOfEscaping>
    <lastPrisonBreakTicks>-1</lastPrisonBreakTicks>
  ");

            //локализуем фракцию роялти
            var tagRoyalty = GameXMLUtils.GetByTag(Data, "royalty");
            if (tagRoyalty != null)
            {
                string oldTR;
                do
                {
                    oldTR = tagRoyalty;
                    tagRoyalty = GameXMLUtils.ReplaceByTag(tagRoyalty, "faction", fractionRoyalty());
                } while (oldTR != tagRoyalty);
                Data = GameXMLUtils.ReplaceByTag(Data, "royalty", tagRoyalty);
            }

            /*
            Data = GameXMLUtils.ReplaceByTag(Data, "hostFaction", "null", "<guest>");
            Data = GameXMLUtils.ReplaceByTag(Data, "prisoner", "False", "<guest>");*/

            /* попытка передавать заключенных не получилась
            Data = GameXMLUtils.ReplaceByTag(Data, "hostFaction", 
                (val) =>
                {
                    if (MainHelper.DebugMode) Loger.Log(" Replace hostFaction "+ val + "=>" + fractionColonist);
                    return val == "null" ? null : fractionColonist;

                });
                */

            //возвращаем true, если это человек и не колонист (пират или пленник)

            if (MainHelper.DebugMode) File.WriteAllText(Loger.PathLog + "MailPawnA" + nnnn.ToString() + ".xml", Data);
            return !col && !isAnimal;
        }

19 Source : GameUtils.cs
with Apache License 2.0
from AantCoder

public static IntVec3 SpawnCaravanPirate(Map map, List<ThingEntry> pawns, Action<Thing, ThingEntry> spawn = null)
        {
            var nextCell = GameUtils.GetAttackCells(map);
            return SpawnList(map, pawns, true, (p) => true, spawn, (p) => nextCell());
        }

19 Source : Wait.cs
with MIT License
from Abc-Arbitrage

public static void Until([InstantHandle] Func<bool> exitCondition, TimeSpan timeout)
        {
            var sw = Stopwatch.StartNew();

            while (sw.Elapsed < timeout)
            {
                if (exitCondition())
                    return;

                Thread.Sleep(10);
            }

            throw new TimeoutException();
        }

19 Source : HighlightingManager.cs
with MIT License
from Abdesol

[System.Diagnostics.Codereplacedysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
															 Justification = "The exception will be rethrown")]
			IHighlightingDefinition GetDefinition()
			{
				Func<IHighlightingDefinition> func;
				lock (lockObj) {
					if (this.definition != null)
						return this.definition;
					func = this.lazyLoadingFunction;
				}
				Exception exception = null;
				IHighlightingDefinition def = null;
				try {
					using (var busyLock = BusyManager.Enter(this)) {
						if (!busyLock.Success)
							throw new InvalidOperationException("Tried to create delay-loaded highlighting definition recursively. Make sure the are no cyclic references between the highlighting definitions.");
						def = func();
					}
					if (def == null)
						throw new InvalidOperationException("Function for delay-loading highlighting definition returned null");
				} catch (Exception ex) {
					exception = ex;
				}
				lock (lockObj) {
					this.lazyLoadingFunction = null;
					if (this.definition == null && this.storedException == null) {
						this.definition = def;
						this.storedException = exception;
					}
					if (this.storedException != null)
						throw new HighlightingDefinitionInvalidException("Error delay-loading highlighting definition", this.storedException);
					return this.definition;
				}
			}

19 Source : RopeNode.cs
with MIT License
from Abdesol

internal override RopeNode<T> GetContentNode()
		{
			lock (this) {
				if (this.cachedResults == null) {
					if (this.initializer == null)
						throw new InvalidOperationException("Trying to load this node recursively; or: a previous call to a rope initializer failed.");
					Func<Rope<T>> initializerCopy = this.initializer;
					this.initializer = null;
					Rope<T> resultRope = initializerCopy();
					if (resultRope == null)
						throw new InvalidOperationException("Rope initializer returned null.");
					RopeNode<T> resultNode = resultRope.root;
					resultNode.Publish(); // result is shared between returned rope and the rope containing this function node
					if (resultNode.length != this.length)
						throw new InvalidOperationException("Rope initializer returned rope with incorrect length.");
					if (resultNode.height == 0 && resultNode.contents == null) {
						// ResultNode is another function node.
						// We want to guarantee that GetContentNode() never returns function nodes, so we have to
						// go down further in the tree.
						this.cachedResults = resultNode.GetContentNode();
					} else {
						this.cachedResults = resultNode;
					}
				}
				return this.cachedResults;
			}
		}

19 Source : MyControllerBase.cs
with MIT License
from Abdulrhman5

protected IActionResult StatusCode<T>(CommandResult<T> result, Func<object> successResult)
        {
            if (result.IsSuccessful)
            {
                return Ok(successResult());
            }

            return StatusCode((int)result.Error.StatusCode, result.Error);
        }

19 Source : FdbTuplePackers.cs
with MIT License
from abdullin

public static T DeserializeFormattable<T>(Slice slice, [NotNull] Func<T> factory)
			where T : ITupleFormattable
		{
			var tuple = FdbTupleParser.ParseTuple(slice);
			var value = factory();
			value.FromTuple(tuple);
			return value;
		}

19 Source : TaskHelpers.cs
with MIT License
from abdullin

public static Task<R> Inline<R>([NotNull] Func<R> lambda, CancellationToken ct = default(CancellationToken))
		{
			if (lambda == null) throw new ArgumentNullException("lambda");

			if (ct.IsCancellationRequested) return FromCancellation<R>(ct);
			try
			{
				var res = lambda();
				return Task.FromResult(res);
			}
			catch (Exception e)
			{
				return FromFailure<R>(e, ct);
			}
		}

19 Source : WhenEngineDisposes.cs
with MIT License
from abdullin

public async Task Run() {
                await _run();
                
            }

19 Source : WhenEngineDisposes.cs
with MIT License
from abdullin

public async Task Dispose() {
                await _dispose();
                
            }

19 Source : ResilientTransaction.cs
with MIT License
from Abdulrhman5

public async Task ExecuteAsync(Func<Task> action)
        {
            //Use of an EF Core resiliency strategy when using multiple DbContexts within an explicit BeginTransaction():
            //See: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
            var strategy = _context.Database.CreateExecutionStrategy();
            await strategy.ExecuteAsync(async () =>
            {
                using (var transaction = _context.Database.BeginTransaction())
                {
                    await action();
                    transaction.Commit();
                }
            });
        }

19 Source : InspectorUIUtility.cs
with Apache License 2.0
from abist-co-ltd

public static bool RenderIndentedButton(Func<bool> renderButton)
        {
            bool result = false;
            GUILayout.BeginHorizontal();
            GUILayout.Space(EditorGUI.indentLevel * 15);
            result = renderButton();
            GUILayout.EndHorizontal();
            return result;
        }

19 Source : MixedRealityToolkitConfigurationProfileInspector.cs
with Apache License 2.0
from abist-co-ltd

public override void OnInspectorGUI()
        {
            var configurationProfile = (MixedRealityToolkitConfigurationProfile)target;
            serializedObject.Update();

            if (!RenderMRTKLogoAndSearch())
            {
                CheckEditorPlayMode();
                return;
            }

            CheckEditorPlayMode();

            if (!MixedRealityToolkit.IsInitialized)
            {
                EditorGUILayout.HelpBox("No Mixed Reality Toolkit found in scene.", MessageType.Warning);
                if (InspectorUIUtility.RenderIndentedButton("Add Mixed Reality Toolkit instance to scene"))
                {
                    MixedRealityInspectorUtility.AddMixedRealityToolkitToScene(configurationProfile);
                }
            }

            if (!configurationProfile.IsCustomProfile)
            {
                EditorGUILayout.HelpBox("The Mixed Reality Toolkit's core SDK profiles can be used to get up and running quickly.\n\n" +
                                        "You can use the default profiles provided, copy and customize the default profiles, or create your own.", MessageType.Warning);
                EditorGUILayout.BeginHorizontal();

                if (GUILayout.Button("Copy & Customize"))
                {
                    SerializedProperty targetProperty = null;
                    UnityEngine.Object selectionTarget = null;
                    // If we have an active MRTK instance, find its config profile serialized property
                    if (MixedRealityToolkit.IsInitialized)
                    {
                        selectionTarget = MixedRealityToolkit.Instance;
                        SerializedObject mixedRealityToolkitObject = new SerializedObject(MixedRealityToolkit.Instance);
                        targetProperty = mixedRealityToolkitObject.FindProperty("activeProfile");
                    }
                    MixedRealityProfileCloneWindow.OpenWindow(null, target as BaseMixedRealityProfile, targetProperty, selectionTarget);
                }

                if (MixedRealityToolkit.IsInitialized)
                {
                    if (GUILayout.Button("Create new profiles"))
                    {
                        ScriptableObject profile = CreateInstance(nameof(MixedRealityToolkitConfigurationProfile));
                        var newProfile = profile.Createreplacedet("replacedets/MixedRealityToolkit.Generated/CustomProfiles") as MixedRealityToolkitConfigurationProfile;
                        UnityEditor.Undo.RecordObject(MixedRealityToolkit.Instance, "Create new profiles");
                        MixedRealityToolkit.Instance.ActiveProfile = newProfile;
                        Selection.activeObject = newProfile;
                    }
                }

                EditorGUILayout.EndHorizontal();
                EditorGUILayout.LabelField(string.Empty, GUI.skin.horizontalSlider);
            }

            bool isGUIEnabled = !IsProfileLock((BaseMixedRealityProfile)target) && GUI.enabled;
            GUI.enabled = isGUIEnabled;

            EditorGUI.BeginChangeCheck();
            bool changed = false;

            // Experience configuration
            ExperienceScale experienceScale = (ExperienceScale)targetExperienceScale.intValue;
            EditorGUILayout.PropertyField(targetExperienceScale, TargetScaleContent);

            string scaleDescription = GetExperienceDescription(experienceScale);
            if (!string.IsNullOrEmpty(scaleDescription))
            {
                EditorGUILayout.HelpBox(scaleDescription, MessageType.None);
                EditorGUILayout.Space();
            }

            changed |= EditorGUI.EndChangeCheck();

            EditorGUILayout.BeginHorizontal();

            EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.Width(100));
            GUI.enabled = true; // Force enable so we can view profile defaults

            int prefsSelectedTab = SessionState.GetInt(SelectedTabPreferenceKey, 0);
            SelectedProfileTab = GUILayout.SelectionGrid(prefsSelectedTab, ProfileTabreplacedles, 1, EditorStyles.boldLabel, GUILayout.MaxWidth(125));
            if (SelectedProfileTab != prefsSelectedTab)
            {
                SessionState.SetInt(SelectedTabPreferenceKey, SelectedProfileTab);
            }

            GUI.enabled = isGUIEnabled;
            EditorGUILayout.EndVertical();

            EditorGUILayout.BeginVertical(EditorStyles.helpBox);
            using (new EditorGUI.IndentLevelScope())
            {
                changed |= RenderProfileFuncs[SelectedProfileTab]();
            }
            EditorGUILayout.EndVertical();
            EditorGUILayout.EndHorizontal();

            serializedObject.ApplyModifiedProperties();
            GUI.enabled = true;

            if (changed && MixedRealityToolkit.IsInitialized)
            {
                EditorApplication.delayCall += () => MixedRealityToolkit.Instance.ResetConfiguration(configurationProfile);
            }
        }

19 Source : TypeReferencePropertyDrawer.cs
with Apache License 2.0
from abist-co-ltd

private static List<Type> GetFilteredTypes(SystemTypeAttribute filter)
        {
            var types = new List<Type>();
            var excludedTypes = ExcludedTypeCollectionGetter?.Invoke();

            // We prefer using this over CompilationPipeline.Getreplacedemblies() because
            // some types may come from plugins and other sources that have already
            // been compiled.
            var replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
            foreach (var replacedembly in replacedemblies)
            {
                FilterTypes(replacedembly, filter, excludedTypes, types);
            }

            types.Sort((a, b) => string.Compare(a.FullName, b.FullName, StringComparison.Ordinal));
            return types;
        }

19 Source : MixedRealityProjectConfigurator.cs
with Apache License 2.0
from abist-co-ltd

public static bool IsConfigured(Configurations config)
        {
            if (ConfigurationGetters.ContainsKey(config))
            {
                var configGetter = ConfigurationGetters[config];
                if (configGetter.IsActiveBuildTargetValid())
                {
                    return configGetter.GetAction.Invoke();
                }
            }

            return false;
        }

19 Source : MixedRealityProjectConfigurator.cs
with Apache License 2.0
from abist-co-ltd

public static bool IsProjectConfigured()
        {
            foreach (var configGetter in ConfigurationGetters)
            {
                if (configGetter.Value.IsActiveBuildTargetValid() && !configGetter.Value.GetAction.Invoke())
                {
                    return false;
                }
            }

            return true;
        }

19 Source : HandInteractionHint.cs
with Apache License 2.0
from abist-co-ltd

private bool ShouldHideVisuals()
        {
            // Check hand tracking, if configured to do so
            bool shouldHide = HideIfHandTracked && IsHandTracked();

            // Check the custom show visuals function
            if (!shouldHide)
            {
                shouldHide |= CustomShouldHideVisuals();
            }
            return shouldHide;
        }

19 Source : BasketServiceTestBase.cs
with MIT License
from abpframework

protected virtual async Task<TResult> WithUnitOfWorkAsync<TResult>(AbpUnitOfWorkOptions options, Func<Task<TResult>> func)
        {
            using (var scope = ServiceProvider.CreateScope())
            {
                var uowManager = scope.ServiceProvider.GetRequiredService<IUnitOfWorkManager>();

                using (var uow = uowManager.Begin(options))
                {
                    var result = await func();
                    await uow.CompleteAsync();
                    return result;
                }
            }
        }

19 Source : OrderingServiceTestBase.cs
with MIT License
from abpframework

protected virtual async Task WithUnitOfWorkAsync(AbpUnitOfWorkOptions options, Func<Task> action)
        {
            using (var scope = ServiceProvider.CreateScope())
            {
                var uowManager = scope.ServiceProvider.GetRequiredService<IUnitOfWorkManager>();

                using (var uow = uowManager.Begin(options))
                {
                    await action();

                    await uow.CompleteAsync();
                }
            }
        }

19 Source : WorkFlowInvoker.cs
with Apache License 2.0
from AbpApp

private async Task<ActivityExecutionResult> InvokeActivityAsync(
            WorkflowExecutionContext workflowContext,
            IActivity activity,
            Func<Task<ActivityExecutionResult>> executeAction,
            CancellationToken cancellationToken)
        {
            try
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    workflowContext.Workflow.Status = WorkflowStatus.Aborted;
                    workflowContext.Workflow.FinishedAt = _clock.GetCurrentInstant();
                    return null;
                }

                return await executeAction();
            }
            catch (Exception ex)
            {
                FaultWorkflow(workflowContext, activity, ex);
            }

            return null;
        }

19 Source : AuthorCard.xaml.cs
with MIT License
from Accelerider

private RelayCommand GetCommand(Func<string> urlGetter)
        {
            return new RelayCommand(() =>
            {
                var url = urlGetter();
                if (!string.IsNullOrWhiteSpace(url)) Process.Start(url);
            });
        }

19 Source : AsyncLocker.cs
with MIT License
from Accelerider

public async void Await(Func<Task> task, bool executeAfterUnlocked = true)
        {
            if (task == null) throw new ArgumentNullException(nameof(task));

            if (!IsLocked)
            {
                try
                {
                    IsLocked = true;
                    await task();
                }
                finally
                {
                    IsLocked = false;
                }
            }
            else if (executeAfterUnlocked)
            {
                Unlocked += OnUnlocked;
            }

            void OnUnlocked()
            {
                Unlocked -= OnUnlocked;
                Await(task, executeAfterUnlocked);
            }
        }

19 Source : AsyncLocker.cs
with MIT License
from Accelerider

public async Task AwaitAsync(Func<Task> task, bool executeAfterUnlocked = true)
        {
            if (task == null) throw new ArgumentNullException(nameof(task));

            if (!IsLocked)
            {
                try
                {
                    IsLocked = true;
                    await task();
                }
                finally
                {
                    IsLocked = false;
                }
            }
            else if (executeAfterUnlocked)
            {
                Unlocked += OnUnlocked;
            }

            async void OnUnlocked()
            {
                Unlocked -= OnUnlocked;
                await AwaitAsync(task, executeAfterUnlocked);
            }
        }

19 Source : Guards.cs
with MIT License
from Accelerider

public static void ThrowIfNot(Func<bool> condition)
        {
            ThrowIfNull(condition);
            ThrowIfNot(condition());
        }

19 Source : RelayCommand.cs
with MIT License
from Accelerider

public bool CanExecute()
        {
            return _canExecute?.Invoke() ?? true;
        }

19 Source : RelayCommandAsync.cs
with MIT License
from Accelerider

public bool CanExecute() => _canExecute?.Invoke() ?? true;

19 Source : RelayCommandAsync.cs
with MIT License
from Accelerider

public async Task Execute()
        {
            IsExecuting = true;
            var invoke = _execute?.Invoke();
            if (invoke != null) await invoke;
            IsExecuting = false;
        }

19 Source : PropertyObserverNode.cs
with MIT License
from Accelerider

private void GenerateNextNode()
        {
            var nextProperty = _propertyGetter();
            if (nextProperty == null) return;

            if (!(nextProperty is INotifyPropertyChanged nextInpcObject))
                throw new InvalidOperationException("Trying to subscribe PropertyChanged listener in object that " +
                                                    $"owns '{Next.PropertyName}' property, but the object does not implements INotifyPropertyChanged.");

            Next.SubscribeListenerFor(nextInpcObject);
        }

19 Source : UpgradeService.cs
with MIT License
from Accelerider

private async Task RunInternalAsync(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                bool requiredRetry = false;
                try
                {
                    var tasks = _tasks.Values.ToArray();
                    foreach (var task in tasks)
                    {
                        await task.LoadFromLocalAsync();
                    }

                    var upgradeInfos = await _upgradeInfosGetter();

                    foreach (var task in tasks)
                    {
                        var info = upgradeInfos.FirstOrDefault(
                            item => item.Name.Equals(task.Name, StringComparison.InvariantCultureIgnoreCase));

                        if (info == null) continue;

                        await task.LoadFromRemoteAsync(info);
                    }
                }
                catch (Exception)
                {
                    requiredRetry = true;
                }

                try
                {
                    await Task.Delay(TimeSpan.FromMinutes(requiredRetry
                            ? RetryIntervalBaseMinute
                            : UpgradeIntervalBaseMinute),
                        token);
                }
                catch (TaskCanceledException)
                {
                    // Ignore
                }
            }
        }

19 Source : DataContext.cs
with MIT License
from Accelerider

public void Export<T>(Expression<Func<T>> propertyExpression, string key = null)
        {
            key = key ?? PropertySupport.ExtractPropertyName(propertyExpression);

            if (_exportPropertyGetterDictionary.ContainsKey(key))
                throw new ArgumentException(string.Format(Resources.DataContext_ExportHasBeenExported_Exception, propertyExpression), nameof(propertyExpression));

            var getter = propertyExpression.Compile();

            _exportPropertyGetterDictionary[key] = getter;

            PropertyObserver.Observes(propertyExpression, () =>
            {
                if (!_importPropertySetterDictionary.TryGetValue(key, out var setterDelegates)) return;

                foreach (var setterDelegate in setterDelegates)
                {
                    var setter = (Action<T>)setterDelegate;
                    setter(getter());
                }
            });
        }

19 Source : AsyncRemotePathProvider.cs
with MIT License
from Accelerider

public override async Task<string> GetAsync()
        {
            var path = await _remotePathGetter();
            if (path == null) return await base.GetAsync();

            RemotePaths.TryAdd(path, 0);

            return path;
        }

19 Source : FrmCaptcha.cs
with MIT License
from ACBrNet

private void RefreshCaptcha()
		{
			var primaryTask = Task<Image>.Factory.StartNew(() => getCaptcha());
			primaryTask.ContinueWith(task =>
			{
				if (task.Result.IsNull()) return;

				captchaPictureBox.Image = task.Result;
				captchaTextBox.Text = string.Empty;
			}, CancellationToken.None, TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.NotOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());

			primaryTask.ContinueWith(task => MessageBox.Show(this, task.Exception.InnerExceptions.Select(x => x.Message).replacedtring()),
				CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
		}

19 Source : WizardBuilder.cs
with MIT License
from Accelerider

public WizardablePanel Build(Style style = null)
        {
            var host = new WizardablePanel();
            foreach (var element in _creators.Select(item => item()))
            {
                if (style != null) element.Style = style;
                host.WizardViews.Add(element);
            }

            return host;
        }

19 Source : OnedriveUser.cs
with MIT License
from Accelerider

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (_token != null)
                request.Headers.Authorization = new AuthenticationHeaderValue(request.Headers.Authorization.Scheme, _token.Invoke());
            return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
        }

19 Source : SecureExtensions.cs
with MIT License
from Accelerider

private static T SuppressException<T>(Func<T> function) where T : clreplaced
        {
            try
            {
                return function?.Invoke();
            }
            catch
            {
                return null;
            }
        }

19 Source : PrimitiveMethods.Download.cs
with MIT License
from Accelerider

public static IObservable<(long Offset, int Bytes)> CreateBlockDownloadItem(
            Func<Task<(HttpWebResponse response, Stream inputStream)>> streamPairFactory,
            BlockTransferContext context) => Observable.Create<(long Offset, int Bytes)>(o =>
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken = cancellationTokenSource.Token;

            // Execute copy stream by async.
            Task.Run(async () =>
            {
                try
                {
                    (HttpWebResponse response, Stream outputStream) = await streamPairFactory();

                    using (response)
                    using (var inputStream = response.GetResponseStream())
                    using (outputStream)
                    {
                        byte[] buffer = new byte[128 * 1024];
                        int count;

                        Guards.ThrowIfNull(inputStream);

                        // ReSharper disable once PossibleNullReferenceException
                        while ((count = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                Debug.WriteLine($"[CANCELLED] [{DateTime.Now}] BLOCK DOWNLOAD ITEM ({context.Offset})");
                                o.OnError(new BlockTransferException(context, new OperationCanceledException()));
                                return;
                            }

                            outputStream.Write(buffer, 0, count);
                            o.OnNext((context.Offset, count));
                        }
                    }

                    o.OnCompleted();
                }
                catch (Exception e)
                {
                    o.OnError(new BlockTransferException(context, e));
                }
            }, cancellationToken);

            return () =>
            {
                Debug.WriteLine($"[DISPOSED] [{DateTime.Now}] BLOCK DOWNLOAD ITEM ({context.Offset})");
                cancellationTokenSource.Cancel();
            };
        });

19 Source : ConditionalAction.cs
with GNU Affero General Public License v3.0
from ACEmulator

public Tuple<IActor, IAction> Act()
        {
            bool cond = Condition();

            if (cond)
                return new Tuple<IActor, IAction>(TrueChain.FirstElement.Actor, TrueChain.FirstElement.Action);

            return new Tuple<IActor, IAction>(FalseChain.FirstElement.Actor, FalseChain.FirstElement.Action);
        }

19 Source : LoopAction.cs
with GNU Affero General Public License v3.0
from ACEmulator

public override Tuple<IActor, IAction> Act()
        {
            if (Condition())
                return new Tuple<IActor, IAction>(Body.FirstElement.Actor, Body.FirstElement.Action);

            return base.Act();
        }

19 Source : AutofacBootstrapper.cs
with Microsoft Public License
from achimismaili

protected override void Configure()
        { //  allow base clreplacedes to change bootstrapper settings
            ConfigureBootstrapper();

            //  validate settings
            if (CreateWindowManager == null)
                throw new ArgumentNullException("CreateWindowManager");
            if (CreateEventAggregator == null)
                throw new ArgumentNullException("CreateEventAggregator");

            //  configure container
            var builder = new ContainerBuilder();

            //  register view models
            builder.RegisterreplacedemblyTypes(replacedemblySource.Instance.ToArray())
              //  must be a type with a name that ends with ViewModel
              .Where(type => type.Name.EndsWith("ViewModel"))
              //  must be in a namespace ending with ViewModels
              .Where(type => EnforceNamespaceConvention ? (!(string.IsNullOrWhiteSpace(type.Namespace)) && type.Namespace.EndsWith("ViewModels")) : true)
              //  must implement INotifyPropertyChanged (deriving from PropertyChangedBase will statisfy this)
              .Where(type => type.GetInterface(ViewModelBaseType.Name, false) != null)
              //  registered as self
              .replacedelf()
              //  always create a new one
              .InstancePerDependency();

            //  register views
            builder.RegisterreplacedemblyTypes(replacedemblySource.Instance.ToArray())
              //  must be a type with a name that ends with View
              .Where(type => type.Name.EndsWith("View"))
              //  must be in a namespace that ends in Views
              .Where(type => EnforceNamespaceConvention ? (!(string.IsNullOrWhiteSpace(type.Namespace)) && type.Namespace.EndsWith("Views")) : true)
              //  registered as self
              .replacedelf()
              //  always create a new one
              .InstancePerDependency();

            //  register the single window manager for this container
            builder.Register<IWindowManager>(c => CreateWindowManager()).InstancePerLifetimeScope();
            //  register the single event aggregator for this container
            builder.Register<IEventAggregator>(c => CreateEventAggregator()).InstancePerLifetimeScope();

            //  should we install the auto-subscribe event aggregation handler module?
            if (AutoSubscribeEventAggegatorHandlers)
                builder.RegisterModule<EventAggregationAutoSubscriptionModule>();

            //  allow derived clreplacedes to add to the container
            ConfigureContainer(builder);

            Container = builder.Build();
        }

19 Source : MockProjectFolder.cs
with MIT License
from action-bi-toolkit

public IProjectFolder GetFolder(string name)
        {
            return _createMockFolder();
        }

19 Source : IPowerBIPartConverter.cs
with MIT License
from action-bi-toolkit

public static bool TryGetStream(this Func<Stream> part, out Stream stream)
        { 
            stream = part == null ? null : part();
            return (stream != null);
        }

See More Examples