System.Threading.Tasks.Task.Run(System.Func)

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

4201 Examples 7

19 View Source File : PlatformLoader.cs
License : GNU General Public License v3.0
Project Creator : affederaffe

private async Task<CustomPlatform?> LoadPlatformFromFileAsyncImpl(string fullPath)
        {
            byte[] bundleData = await Task.Run(() => File.ReadAllBytes(fullPath));
            replacedetBundle replacedetBundle = await LoadreplacedetBundleFromBytesAsync(bundleData);

            if (replacedetBundle == null)
            {
                _siraLog.Error($"File could not be loaded:\n{fullPath}");
                return null;
            }

            GameObject platformPrefab = await LoadreplacedetFromreplacedetBundleAsync<GameObject>(replacedetBundle, "_CustomPlatform");

            if (platformPrefab == null)
            {
                replacedetBundle.Unload(true);
                _siraLog.Error($"Platform GameObject could not be loaded:\n{fullPath}");
                return null;
            }

            replacedetBundle.Unload(false);

            CustomPlatform? customPlatform = platformPrefab.GetComponent<CustomPlatform>();

            if (customPlatform is null)
            {
                // Check for old platform 
                global::CustomPlatform? legacyPlatform = platformPrefab.GetComponent<global::CustomPlatform>();
                if (legacyPlatform is not null)
                {
                    // Replace legacy platform component with up to date one
                    customPlatform = platformPrefab.AddComponent<CustomPlatform>();
                    customPlatform.platName = legacyPlatform.platName;
                    customPlatform.platAuthor = legacyPlatform.platAuthor;
                    customPlatform.hideDefaultPlatform = true;
                    // Remove old platform data
                    UnityEngine.Object.Destroy(legacyPlatform);
                }
                else
                {
                    // No CustomPlatform component, abort
                    UnityEngine.Object.Destroy(platformPrefab);
                    _siraLog.Error($"replacedetBundle does not contain a CustomPlatform:\n{fullPath}");
                    return null;
                }
            }

            Camera[] cameras = platformPrefab.GetComponentsInChildren<Camera>(true);
            foreach (Camera camera in cameras)
            {
                BloomPrePreplaced bloomPrePreplaced = camera.gameObject.AddComponent<BloomPrePreplaced>();
                bloomPrePreplaced.SetField("_bloomPrepreplacedRenderer", _bloomPrepreplacedRenderer);
                bloomPrePreplaced.SetField("_bloomPrePreplacedEffectContainer", _bloomPrePreplacedEffectContainer);
            }

            customPlatform.platHash = await Task.Run(() => ComputeHash(bundleData));
            customPlatform.fullPath = fullPath;
            customPlatform.name = $"{customPlatform.platName} by {customPlatform.platAuthor}";

            await _materialSwapper.ReplaceMaterialsAsync(customPlatform.gameObject);

            return customPlatform;
        }

19 View Source File : RestClient.cs
License : MIT License
Project Creator : Aiko-IT-Systems

private void UpdateBucket(BaseRestRequest request, RestResponse response, TaskCompletionSource<bool> ratelimitTcs)
        {
            var bucket = request.RateLimitBucket;

            if (response.Headers == null)
            {
                if (response.ResponseCode != 429) // do not fail when ratelimit was or the next request will be scheduled hitting the rate limit again
                    this.FailInitialRateLimitTest(request, ratelimitTcs);
                return;
            }

            var hs = response.Headers;

            if (hs.TryGetValue("X-RateLimit-Global", out var isglobal) && isglobal.ToLowerInvariant() == "true")
            {
                if (response.ResponseCode != 429)
                    this.FailInitialRateLimitTest(request, ratelimitTcs);

                return;
            }

            var r1 = hs.TryGetValue("X-RateLimit-Limit", out var usesmax);
            var r2 = hs.TryGetValue("X-RateLimit-Remaining", out var usesleft);
            var r3 = hs.TryGetValue("X-RateLimit-Reset", out var reset);
            var r4 = hs.TryGetValue("X-Ratelimit-Reset-After", out var resetAfter);
            var r5 = hs.TryGetValue("X-Ratelimit-Bucket", out var hash);

            if (!r1 || !r2 || !r3 || !r4)
            {
                //If the limits were determined before this request, make the bucket initial again.
                if (response.ResponseCode != 429)
                    this.FailInitialRateLimitTest(request, ratelimitTcs, ratelimitTcs == null);

                return;
            }

            var clienttime = DateTimeOffset.UtcNow;
            var resettime = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddSeconds(double.Parse(reset, CultureInfo.InvariantCulture));
            var servertime = clienttime;
            if (hs.TryGetValue("Date", out var raw_date))
                servertime = DateTimeOffset.Parse(raw_date, CultureInfo.InvariantCulture).ToUniversalTime();

            var resetdelta = resettime - servertime;
            //var difference = clienttime - servertime;
            //if (Math.Abs(difference.TotalSeconds) >= 1)
            ////    this.Logger.LogMessage(LogLevel.DebugBaseDiscordClient.RestEventId,  $"Difference between machine and server time: {difference.TotalMilliseconds.ToString("#,##0.00", CultureInfo.InvariantCulture)}ms", DateTime.Now);
            //else
            //    difference = TimeSpan.Zero;

            if (request.RateLimitWaitOverride.HasValue)
                resetdelta = TimeSpan.FromSeconds(request.RateLimitWaitOverride.Value);
            var newReset = clienttime + resetdelta;

            if (this.UseResetAfter)
            {
                bucket.ResetAfter = TimeSpan.FromSeconds(double.Parse(resetAfter, CultureInfo.InvariantCulture));
                newReset = clienttime + bucket.ResetAfter.Value + (request.RateLimitWaitOverride.HasValue
                    ? resetdelta
                    : TimeSpan.Zero);
                bucket.ResetAfterOffset = newReset;
            }
            else
                bucket.Reset = newReset;

            var maximum = int.Parse(usesmax, CultureInfo.InvariantCulture);
            var remaining = int.Parse(usesleft, CultureInfo.InvariantCulture);

            if (ratelimitTcs != null)
            {
                // initial population of the ratelimit data
                bucket.SetInitialValues(maximum, remaining, newReset);

                _ = Task.Run(() => ratelimitTcs.TrySetResult(true));
            }
            else
            {
                // only update the bucket values if this request was for a newer interval than the one
                // currently in the bucket, to avoid issues with concurrent requests in one bucket
                // remaining is reset by TryResetLimit and not the response, just allow that to happen when it is time
                if (bucket._nextReset == 0)
                    bucket._nextReset = newReset.UtcTicks;
            }

            this.UpdateHashCaches(request, bucket, hash);
        }

19 View Source File : HandleMessageTest.cs
License : MIT License
Project Creator : AdemCatamak

[ReleaseModeTheory]
        [InlineData(1, 1000, 10000)]
        [InlineData(2, 1000, 7500)]
        [InlineData(4, 1000, 5000)]
        [InlineData(1, 100, 1500)]
        [InlineData(2, 100, 1000)]
        [InlineData(4, 100, 750)]
        public void When_JobHandledCalledWithParallel__ResponseTimeShouldNotExceed(int parallelJobCount, int times, int expectedMilliseconds)
        {
            List<Task> addTasks = new List<Task>();
            for (var i = 0; i < times; i++)
            {
                DummyMessage dummyMessage = new DummyMessage
                {
                    Guid = Guid.NewGuid()
                };
                var task = _messageStorageClient.AddMessageAsync(dummyMessage);
                addTasks.Add(task);
            }

            Task.WaitAll(addTasks.ToArray());
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            List<Task> jobProcessorTasks = new List<Task>();
            for (var i = 0; i < parallelJobCount; i++)
            {
                Task task = Task.Run(async () =>
                                     {
                                         bool jobHandled;
                                         do
                                         {
                                             jobHandled = await _jobDispatcher.HandleNextJobAsync();
                                         } while (jobHandled);
                                     }
                                    );
                jobProcessorTasks.Add(task);
            }

            Task.WaitAll(jobProcessorTasks.ToArray());

            stopwatch.Stop();

            string message = $"Parallel Job Count : {parallelJobCount}{Environment.NewLine}" +
                             $"Executed Job Count : {times}{Environment.NewLine}" +
                             $"Expected Execution Time : {expectedMilliseconds} ms{Environment.NewLine}" +
                             $"Actual Execution Time : {stopwatch.ElapsedMilliseconds} ms";
            replacedertThat.LessThan(expectedMilliseconds, stopwatch.ElapsedMilliseconds, message);
            _output.WriteLine(message);
        }

19 View Source File : TaskQueueTests.cs
License : MIT License
Project Creator : AElfProject

private async Task ProcessTask()
        {
            await Task.Run(() => _counter++);
        }

19 View Source File : PostToFlow.cs
License : MIT License
Project Creator : adoprog

public override void Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext = null,
      params object[] data)
    {
      replacedert.ArgumentNotNull(adaptedFields, nameof(adaptedFields));

      var requestor = new Requestor();
      var fields = GetFieldsJson(adaptedFields);
      Task.Run(() => requestor.PostRequest(TriggerAddress, fields));
    }

19 View Source File : Avatar.razor.cs
License : MIT License
Project Creator : ADefWebserver

public async ValueTask CreateScene()
        {
            var canvas = await Canvas.GetElementById(
                "game-window"
            );
            var engine = await Engine.NewEngine(
                canvas,
                true
            );
            var scene = await Scene.NewScene(
                engine
            );
            var light0 = await PointLight.NewPointLight(
                "Omni",
                await Vector3.NewVector3(
                    0,
                    100,
                    8
                ),
                scene
            );
            var light1 = await HemisphericLight.NewHemisphericLight(
                "HemisphericLight",
                await Vector3.NewVector3(
                    0,
                    100,
                    8
                ),
                scene
            );

            var Player = await SceneLoader.ImportMesh(
                null,
                "replacedets/",
                "Player.glb",
                scene,
               new ActionCallback<AbstractMesh[], IParticleSystem[], Skeleton[], AnimationGroup[], TransformNode[], Geometry[], Light[]>(async (arg1, arg2, arg3, arg4, arg5, arg6, arg7) =>
               {
                    foreach (var animation in arg4)
                    {
                        await animation.stop();
                        _animationMap.Add(await animation.get_name(), animation);
                    }
                    if (_animationMap.Count > 0)
                    {
                        _runningAnimation = _animationMap.First().Value;
                        await _runningAnimation.start(true);
                    }
                })
            );            

            var camera = await ArcRotateCamera.NewArcRotateCamera(
                "ArcRotateCamera",
                (decimal)(System.Math.PI / 2),
                (decimal)(System.Math.PI / 4),
                3,
                await Vector3.NewVector3(0, 1, 0),
                scene
            );

            await camera.set_lowerRadiusLimit(2);
            await camera.set_upperRadiusLimit(10);
            await camera.set_wheelDeltaPercentage(0.01m);

            await scene.set_activeCamera(camera);

            await scene.set_activeCamera(camera);

            await camera.attachControl(
                false
            );

            await engine.runRenderLoop(new ActionCallback(
                            () => Task.Run(() => scene.render(true, false))
                        ));

            _engine = engine;
        }

19 View Source File : KeyRingProviderTest.cs
License : Apache License 2.0
Project Creator : Aguafrommars

[Fact]
        public void GetCurrentKeyRing_NoExistingKeyRing_HoldsAllThreadsUntilKeyRingCreated()
        {
            // Arrange
            var now = StringToDateTime("2015-03-01 00:00:00Z");
            var expectedKeyRing = new Mock<IKeyRing>().Object;
            var mockCacheableKeyRingProvider = new Mock<ICacheableKeyRingProvider>();
            var keyRingProvider = CreateKeyRingProvider(mockCacheableKeyRingProvider.Object);

            // This test spawns a background thread which calls GetCurrentKeyRing then waits
            // for the foreground thread to call GetCurrentKeyRing. When the foreground thread
            // blocks (inside the lock), the background thread will return the cached keyring
            // object, and the foreground thread should consume that same object instance.

            TimeSpan testTimeout = TimeSpan.FromSeconds(10);

            Thread foregroundThread = Thread.CurrentThread;
            ManualResetEventSlim mreBackgroundThreadHasCalledGetCurrentKeyRing = new ManualResetEventSlim();
            ManualResetEventSlim mreForegroundThreadIsCallingGetCurrentKeyRing = new ManualResetEventSlim();
            var backgroundGetKeyRingTask = Task.Run(() =>
            {
                mockCacheableKeyRingProvider
                    .Setup(o => o.GetCacheableKeyRing(now))
                    .Returns(() =>
                    {
                        mreBackgroundThreadHasCalledGetCurrentKeyRing.Set();
                        replacedert.True(mreForegroundThreadIsCallingGetCurrentKeyRing.Wait(testTimeout), "Test timed out.");
                        SpinWait.SpinUntil(() => (foregroundThread.ThreadState & ThreadState.WaitSleepJoin) != 0, testTimeout);
                        return new CacheableKeyRing(
                            expirationToken: CancellationToken.None,
                            expirationTime: StringToDateTime("2015-03-02 00:00:00Z"),
                            keyRing: expectedKeyRing);
                    });

                return keyRingProvider.GetCurrentKeyRingCore(now);
            });

            replacedert.True(mreBackgroundThreadHasCalledGetCurrentKeyRing.Wait(testTimeout), "Test timed out.");
            mreForegroundThreadIsCallingGetCurrentKeyRing.Set();
            var foregroundRetVal = keyRingProvider.GetCurrentKeyRingCore(now);
            backgroundGetKeyRingTask.Wait(testTimeout);
            var backgroundRetVal = backgroundGetKeyRingTask.GetAwaiter().GetResult();

            // replacedert - underlying provider only should have been called once
            replacedert.Same(expectedKeyRing, foregroundRetVal);
            replacedert.Same(expectedKeyRing, backgroundRetVal);
            mockCacheableKeyRingProvider.Verify(o => o.GetCacheableKeyRing(It.IsAny<DateTimeOffset>()), Times.Once);
        }

19 View Source File : AscReader.cs
License : MIT License
Project Creator : ABTSoftware

public static async Task<AscData> ReadFileToAscData(
            string filename, Func<float, Color> colorMapFunction, Action<int> reportProgress = null)
        {
            var result = await Task.Run(() =>
            {
                using (var file = File.OpenText(filename))
                {
                    return ReadFromStream(file, colorMapFunction, reportProgress);
                }
            });

            return result;
        }

19 View Source File : CommandsNextExtension.cs
License : MIT License
Project Creator : Aiko-IT-Systems

private async Task HandleCommandsAsync(DiscordClient sender, MessageCreateEventArgs e)
        {
            if (e.Author.IsBot) // bad bot
                return;

            if (!this.Config.EnableDms && e.Channel.IsPrivate)
                return;

            var mpos = -1;
            if (this.Config.EnableMentionPrefix)
                mpos = e.Message.GetMentionPrefixLength(this.Client.CurrentUser);

            if (this.Config.StringPrefixes?.Any() == true)
                foreach (var pfix in this.Config.StringPrefixes)
                    if (mpos == -1 && !string.IsNullOrWhiteSpace(pfix))
                        mpos = e.Message.GetStringPrefixLength(pfix, this.Config.CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);

            if (mpos == -1 && this.Config.PrefixResolver != null)
                mpos = await this.Config.PrefixResolver(e.Message).ConfigureAwait(false);

            if (mpos == -1)
                return;

            var pfx = e.Message.Content.Substring(0, mpos);
            var cnt = e.Message.Content.Substring(mpos);

            var __ = 0;
            var fname = cnt.ExtractNextArgument(ref __);

            var cmd = this.FindCommand(cnt, out var args);
            var ctx = this.CreateContext(e.Message, pfx, cmd, args);
            if (cmd == null)
            {
                await this._error.InvokeAsync(this, new CommandErrorEventArgs(this.Client.ServiceProvider) { Context = ctx, Exception = new CommandNotFoundException(fname) }).ConfigureAwait(false);
                return;
            }

            _ = Task.Run(async () => await this.ExecuteCommandAsync(ctx).ConfigureAwait(false));
        }

19 View Source File : InMemoryDataBase.cs
License : Microsoft Public License
Project Creator : achimismaili

public async Task<bool> LoadAsync()
        {
            var trueWhenDone = await Task.Run<bool>(() =>
            {
               return Load();
            });

            return trueWhenDone;
        }

19 View Source File : AElfKeyStore.cs
License : MIT License
Project Creator : AElfProject

public async Task<List<string>> GetAccountsAsync()
        {
            var dir = CreateKeystoreDirectory();
            var files = dir.GetFiles("*" + KeyFileExtension);

            return await Task.Run(() => files.Select(f => Path.GetFileNameWithoutExtension(f.Name)).ToList());
        }

19 View Source File : SendToFlow.cs
License : MIT License
Project Creator : adoprog

protected override bool Execute(SendToFlowActionData data, FormSubmitContext formSubmitContext)
    {
      replacedert.ArgumentNotNull(formSubmitContext, "formSubmitContext");
      if (string.IsNullOrEmpty(data.TriggerAddress))
      {
        return false;
      }

      var requestor = new Requestor();
      var fields = GetFieldsJson(formSubmitContext.Fields);
      Task.Run(() => requestor.PostRequest(data.TriggerAddress, fields));

      return true;
    }

19 View Source File : PXRegexColorizerTagger.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

protected internal async override Task<IEnumerable<ITagSpan<IClreplacedificationTag>>> GetTagsAsyncImplementationAsync(ITextSnapshot snapshot,
                                                                                                               CancellationToken cancellationToken)
        {
            var taggingInfo = await Task.Run(() => GetTagsSynchronousImplementation(snapshot))
                                        .TryAwait();

            if (!taggingInfo.IsSuccess)
                return Enumerable.Empty<ITagSpan<IClreplacedificationTag>>();

            return taggingInfo.Result;
        }

19 View Source File : AssetLoader.cs
License : GNU General Public License v3.0
Project Creator : affederaffe

private async Task<GameObject> CreatePlayersPlaceAsync()
        {
            (Vector3[] vertices, int[] triangles) = await Task.Run(() => ParseMesh("CustomFloorPlugin.replacedets.PlayersPlace.mesh"));
            Mesh mesh = new()
            {
                vertices = vertices,
                triangles = triangles
            };

            GameObject playersPlaceCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            playersPlaceCube.SetActive(false);
            MeshRenderer cubeRenderer = playersPlaceCube.GetComponent<MeshRenderer>();
            (Material darkEnvSimpleMaterial, _, _) = await _materialSwapper.MaterialsTask;
            cubeRenderer.material = darkEnvSimpleMaterial;
            playersPlaceCube.transform.localPosition = new Vector3(0f, -50.0075f, 0f);
            playersPlaceCube.transform.localScale = new Vector3(3f, 100f, 2f);
            playersPlaceCube.name = "PlayersPlace";

            GameObject playersPlaceMirror = GameObject.CreatePrimitive(PrimitiveType.Plane);
            playersPlaceMirror.name = "Mirror";
            playersPlaceMirror.transform.SetParent(playersPlaceCube.transform);
            playersPlaceMirror.transform.localScale = new Vector3(0.1f, 0f, 0.1f);
            playersPlaceMirror.transform.localPosition = new Vector3(0f, 0.5001f, 0f);
            TrackMirror trackMirror = playersPlaceMirror.AddComponent<TrackMirror>();
            trackMirror.bumpIntensity = 0.02f;
            using Stream floorStream = GetEmbeddedResource("CustomFloorPlugin.replacedets.Floor.png");
            trackMirror.normalTexture = floorStream.ReadTexture2D();
            trackMirror.PlatformEnabled(_container);

            GameObject playersPlaceFrame = new("Frame");
            playersPlaceFrame.transform.SetParent(playersPlaceCube.transform);
            playersPlaceFrame.AddComponent<MeshRenderer>();
            MeshFilter meshFilter = playersPlaceFrame.AddComponent<MeshFilter>();
            meshFilter.mesh = mesh;
            TubeLight tubeLight = playersPlaceFrame.AddComponent<TubeLight>();
            tubeLight.color = Color.blue;
            tubeLight.PlatformEnabled(_container);

            return playersPlaceCube;
        }

19 View Source File : MeshSmoother.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public Task SmoothNormalsAsync()
        {
            Mesh mesh;

            // No need to do any smoothing if this mesh has already been processed.
            if (AcquirePreprocessedMesh(out mesh))
            {
                return Task.CompletedTask;
            }

            // Create a copy of the vertices and normals and apply the smoothing in an async task.
            var vertices = mesh.vertices;
            var normals = mesh.normals;
            var asyncTask = Task.Run(() => CalculateSmoothNormals(vertices, normals));

            // Once the async task is complete, apply the smoothed normals to the mesh on the main thread.
            return asyncTask.ContinueWith((i) =>
            {
                mesh.SetUVs(smoothNormalUVChannel, i.Result);
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }

19 View Source File : UserOnlyStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public async override Task<IList<TUser>> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            replacedertNotNull(claim, nameof(claim));

            Dictionary<string, TUserClaim> data;
            try
            {
                var response = await _client.GetAsync<Dictionary<string, TUserClaim>>(GetFirebasePath(UserClaimsTableName), cancellationToken, false, $"orderBy=\"ClaimType\"&equalTo=\"{claim.Type}\"")
                    .ConfigureAwait(false);
                data = response.Data;
            }
            catch (FirebaseException e)
                when (e.FirebaseError != null && e.FirebaseError.Error.StartsWith("Index"))
            {
                await SetIndex(UserClaimsTableName, new UserClaimIndex(), cancellationToken)
                    .ConfigureAwait(false);

                var response = await _client.GetAsync<Dictionary<string, TUserClaim>>(GetFirebasePath(UserClaimsTableName), cancellationToken, queryString: $"orderBy=\"ClaimType\"&equalTo=\"{claim.Type}\"")
                    .ConfigureAwait(false);
                data = response.Data;
            }

            if (data == null)
            {
                return new List<TUser>(0);
            }

            var userIds = data.Values.Where(c => c.ClaimValue == claim.Value).Select(c => c.UserId);
            var users = new ConcurrentBag<TUser>();
            var taskList = new List<Task>(userIds.Count());
            foreach (var userId in userIds)
            {
                taskList.Add(Task.Run(async () => {
                    var user = await FindByIdAsync(userId, cancellationToken)
                        .ConfigureAwait(false);
                    if (user != null)
                    {
                        users.Add(user);
                    }
                }));
            }

            await Task.WhenAll(taskList.ToArray())
                .ConfigureAwait(false);

            return users.ToList();
        }

19 View Source File : HandleMessageTest.cs
License : MIT License
Project Creator : AdemCatamak

[ReleaseModeTheory]
        [InlineData(1, 1000, 10000)]
        [InlineData(2, 1000, 7500)]
        [InlineData(4, 1000, 5000)]
        [InlineData(1, 100, 1500)]
        [InlineData(2, 100, 1000)]
        [InlineData(4, 100, 750)]
        public void When_JobHandledCalledWithParallel__ResponseTimeShouldNotExceed(int concurrentJobCount, int times, int expectedMilliseconds)
        {
            List<Task> tasks = new List<Task>();
            for (var i = 0; i < times; i++)
            {
                DummyMessage dummyMessage = new DummyMessage
                {
                    Guid = Guid.NewGuid()
                };
                var task = _messageStorageClient.AddMessageAsync(dummyMessage);
                tasks.Add(task);
            }

            Task.WaitAll(tasks.ToArray());
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            List<Task> jobProcessorTasks = new List<Task>();
            for (var i = 0; i < concurrentJobCount; i++)
            {
                Task task = Task.Run(async () =>
                                     {
                                         bool jobHandled;
                                         do
                                         {
                                             jobHandled = await _jobDispatcher.HandleNextJobAsync();
                                         } while (jobHandled);
                                     }
                                    );
                jobProcessorTasks.Add(task);
            }

            Task.WaitAll(jobProcessorTasks.ToArray());

            stopwatch.Stop();

            string message = $"Parallel Job Count : {concurrentJobCount}{Environment.NewLine}" +
                             $"Executed Job Count : {times}{Environment.NewLine}" +
                             $"Expected Execution Time : {expectedMilliseconds} ms{Environment.NewLine}" +
                             $"Actual Execution Time : {stopwatch.ElapsedMilliseconds} ms";
            replacedertThat.LessThan(expectedMilliseconds, stopwatch.ElapsedMilliseconds, message);
            _output.WriteLine(message);
        }

19 View Source File : AzureBlobXmlRepository.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public void StoreElement(XElement element, string friendlyName)
        {
            if (element == null)
            {
                throw new ArgumentNullException(nameof(element));
            }

            // Shunt the work onto a ThreadPool thread so that it's independent of any
            // existing sync context or other potentially deadlock-causing items.

            Task.Run(() => StoreElementAsync(element)).GetAwaiter().GetResult();
        }

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

static void Main(string[] args)
        {

            sedb.StringSet("key1", (string)null);

            var val111 = sedb.StringGet("key1");














            RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,asyncPipeline=true,preheat=100,poolsize=100"));
            cli.Set("TestMGet_null1", "");
            RedisHelper.Set("TestMGet_null1", "");
            sedb.StringSet("TestMGet_string1", String);
            ThreadPool.SetMinThreads(10001, 10001);
            Stopwatch sw = new Stopwatch();
            var tasks = new List<Task>();
            var results = new ConcurrentQueue<string>();

            cli.FlushDb();
            results.Clear();
            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                sedb.StringSet(tmp, String);
                var val = sedb.StringGet(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("StackExchange(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    sedb.StringSet(tmp, String);
                    var val = sedb.StringGet(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchange(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                cli.Set(tmp, String);
                var val = cli.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("FreeRedis(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    cli.Set(tmp, String);
                    var val = cli.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("FreeRedis(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //Task.Run(async () =>
            //{
            //    for (var a = 0; a < 100000; a++)
            //    {
            //        var tmp = Guid.NewGuid().ToString();
            //        await cli.SetAsync(tmp, String);
            //        var val = await cli.GetAsync(tmp);
            //        if (val != String) throw new Exception("not equal");
            //        results.Enqueue(val);
            //    }
            //}).Wait();
            //sw.Stop();
            //Console.WriteLine("FreeRedisAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            //tasks.Clear();
            //results.Clear();
            //cli.FlushDb();

            //FreeRedis.Internal.AsyncRedisSocket.sb.Clear();
            //FreeRedis.Internal.AsyncRedisSocket.sw.Start();
            //sw.Reset();
            //sw.Start();
            //tasks = new List<Task>();
            //for (var a = 0; a < 100000; a++)
            //{
            //    tasks.Add(Task.Run(async () =>
            //    {
            //        var tmp = Guid.NewGuid().ToString();
            //        await cli.SetAsync(tmp, String);
            //        var val = await cli.GetAsync(tmp);
            //        if (val != String) throw new Exception("not equal");
            //        results.Enqueue(val);
            //    }));
            //}
            //Task.WaitAll(tasks.ToArray());
            //sw.Stop();
            ////var sbstr = FreeRedis.Internal.AsyncRedisSocket.sb.ToString()
            ////sbstr = sbstr + sbstr.Split("\r\n").Length + "条消息 ;
            //Console.WriteLine("FreeRedisAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            //tasks.Clear();
            //results.Clear();
            //cli.FlushDb();

            sw.Reset();
            sw.Start();
            using (var pipe = cli.StartPipe())
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    pipe.Set(tmp, String);
                    var val = pipe.Get(tmp);
                }
                var vals = pipe.EndPipe();
                for (var a = 1; a < 200000; a += 2)
                {
                    var val = vals[a].ToString();
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }
            sw.Stop();
            Console.WriteLine("FreeRedisPipeline(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //    cli.Call(new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String));
            //sw.Stop();
            //Console.WriteLine("FreeRedis2: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //{
            //    using (var rds = cli.GetTestRedisSocket())
            //    {
            //        var cmd = new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String);
            //        rds.Write(cmd);
            //        cmd.Read<string>();
            //    }
            //}
            //sw.Stop();
            //Console.WriteLine("FreeRedis4: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                RedisHelper.Set(tmp, String);
                var val = RedisHelper.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("CSRedisCore(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    RedisHelper.Set(tmp, String);
                    var val = RedisHelper.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCore(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    //if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();
        }

19 View Source File : AsyncManualResetEvent.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public Task SetAsync() => Task.Run(() => this._tsc.TrySetResult(true));

19 View Source File : JobDispatcher_HandleNextJobAsync_Test.cs
License : MIT License
Project Creator : AdemCatamak

[Theory]
        [InlineData(1, 100)]
        [InlineData(4, 100)]
        [InlineData(8, 100)]
        [InlineData(1, 300)]
        [InlineData(4, 300)]
        [InlineData(8, 300)]
        [InlineData(12, 300)]
        [InlineData(16, 300)]
        [InlineData(1, 1000)]
        [InlineData(4, 1000)]
        [InlineData(8, 1000)]
        [InlineData(12, 1000)]
        [InlineData(16, 1000)]
        public void When_JobHandledCalledWithParallel__InitialJobCountAndJobExecutionCountShouldBeEqual(int parallelJobCount, int initialJobCount)
        {
            List<Task> addTasks = new List<Task>();
            for (var i = 0; i < initialJobCount; i++)
            {
                DummyMessage dummyMessage = new DummyMessage
                {
                    Guid = Guid.NewGuid()
                };
                var task = _messageStorageClient.AddMessageAsync(dummyMessage);
                addTasks.Add(task);
            }

            Task.WaitAll(addTasks.ToArray());

            List<Task> jobProcessorTasks = new List<Task>();
            int actualExecutedJobCount = 0;
            for (var i = 0; i < parallelJobCount; i++)
            {
                Task task = Task.Run(async () =>
                                     {
                                         bool jobHandled;
                                         do
                                         {
                                             jobHandled = await _sut.HandleNextJobAsync();
                                             if (jobHandled)
                                             {
                                                 Interlocked.Increment(ref actualExecutedJobCount);
                                             }
                                         } while (jobHandled);
                                     }
                                    );
                jobProcessorTasks.Add(task);
            }

            Task.WaitAll(jobProcessorTasks.ToArray());

            string message = $"Parallel Job Count : {parallelJobCount}{Environment.NewLine}" +
                             $"Expected Executed Job Count : {initialJobCount}{Environment.NewLine}" +
                             $"Actual Executed Job Count : {actualExecutedJobCount}";
            replacedert.Equal(initialJobCount, actualExecutedJobCount);
            _output.WriteLine(message);
        }

19 View Source File : CustomIconProvider.uwp.cs
License : MIT License
Project Creator : adenearnshaw

public async Task<object> CreatePlatformIcon(IShortcutIcon shortcutIcon)
        {
            return await Task.Run(() =>
            {
                var uri = $"ms-appx:///{shortcutIcon.IconName}";
                return new Uri(uri);
            });
        }

19 View Source File : ConfigDomainService.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<Dictionary<string, string>> GetConfigsFromDb()
        {
            return await Task.Run(() =>
            {
                var configurations = _redisDb.HashGetAll("configurations");
                return configurations.ToDictionary(x => x.Name.ToString(), x => x.Value.ToString());
            });

        }

19 View Source File : SendToFlow.cs
License : MIT License
Project Creator : adoprog

public ActivityResult Invoke(IContactProcessingContext context)
    {
      var contact = context.Contact;
      if (!contact.IsKnown)
      {
        return (ActivityResult)new SuccessMove();
      }

      if (!contact.ExpandOptions.FacetKeys.Contains(PersonalInformation.DefaultFacetKey))
      {
        var expandOptions = new ContactExpandOptions(PersonalInformation.DefaultFacetKey, EmailAddressList.DefaultFacetKey);
        contact = Services.Collection.GetContactAsync(contact, expandOptions).ConfigureAwait(false).GetAwaiter().GetResult();
      }

      var emailFacets = contact.GetFacet<EmailAddressList>();
      var personalInfo = contact.GetFacet<PersonalInformation>();
      var fields = "{" +
                   "\"Email\": \"" + emailFacets.PreferredEmail?.SmtpAddress + "\", " +
                   "\"FirstName\": \"" + personalInfo.FirstName + "\", " +
                   "\"MiddleName\": \"" + personalInfo.MiddleName + "\", " +
                   "\"LastName\": \"" + personalInfo.LastName + "\", " +
                   "\"PreferredLanguage\": \"" + personalInfo.PreferredLanguage + "\", " +
                   "\"replacedle\": \"" + personalInfo.replacedle + "\", " +
                   "\"Jobreplacedle\": \"" + personalInfo.Jobreplacedle + "\" " +
                   "}";
      Task.Run(() => PostRequest(triggerAddress, fields));

      return (ActivityResult) new SuccessMove();
    }

19 View Source File : SingletonDb.cs
License : Microsoft Public License
Project Creator : achimismaili

private static async Task<InMemoryDataBase> CreateDbAsync()
        {
            var db = await Task.Run<InMemoryDataBase>(() =>
            {
                return CreateDb();
            });

            return db;
        }

19 View Source File : GrpcCrossChainServer.cs
License : MIT License
Project Creator : AElfProject

public async Task StartAsync(int listeningPort)
        {
            _server = new global::Grpc.Core.Server
            {
                Ports =
                {
                    new ServerPort(IPAddress.Any.ToString(), listeningPort, ServerCredentials.Insecure)
                },
                Services =
                {
                    ParentChainRpc.BindService(_grpcParentChainServerBase),
                    SideChainRpc.BindService(_grpcSideChainServerBase),
                    BasicCrossChainRpc.BindService(_grpcBasicServerBase)
                }
            };

            await Task.Run(() => _server.Start());

            Logger.LogInformation($"Grpc cross chain server started, listening at {listeningPort}");
            IsStarted = true;
        }

19 View Source File : Kissing.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void TrySpousesKiss(GameLocation location)
        {

            if ( location == null || Game1.eventUp || Game1.activeClickableMenu != null || Game1.player.currentLocation != location || (!Config.AllowNPCSpousesToKiss && !Config.AllowPlayerSpousesToKiss && !Config.AllowNPCRelativesToHug))
                return;

            elapsedSeconds++;

            var characters = location.characters;
            if (characters == null)
                return;

            List<NPC> list = characters.ToList();

            Misc.ShuffleList(ref list);

            foreach (NPC npc1 in list)
            {
                if (!npc1.datable.Value && !npc1.isRoommate() && !Config.AllowNonDateableNPCsToHugAndKiss)
                    continue;

                foreach (NPC npc2 in list)
                {
                    if (npc1.Name == npc2.Name)
                        continue;

                    if (!npc2.datable.Value && !Config.AllowNonDateableNPCsToHugAndKiss)
                        continue;

                    if (lastKissed.ContainsKey(npc1.Name) && elapsedSeconds - lastKissed[npc1.Name] <= Config.MinSpouseKissIntervalSeconds)
                        continue;

                    if (lastKissed.ContainsKey(npc2.Name) && elapsedSeconds - lastKissed[npc2.Name] <= Config.MinSpouseKissIntervalSeconds)
                        continue;

                    bool npcRelatedHug = Misc.AreNPCsRelated(npc1.Name, npc2.Name) && Config.AllowNPCRelativesToHug;
                    bool npcRoommateHug = !Config.RoommateKisses && (npc1.isRoommate() || npc2.isRoommate());
                    
                    bool npcMarriageKiss = Misc.AreNPCsMarried(npc1.Name, npc2.Name) && Config.AllowNPCSpousesToKiss;
                    bool playerSpouseKiss = Config.AllowPlayerSpousesToKiss &&
                        npc1.getSpouse() != null && npc2.getSpouse() != null &&
                        npc1.getSpouse() == npc2.getSpouse() &&
                        npc1.getSpouse().friendshipData.ContainsKey(npc1.Name) && npc1.getSpouse().friendshipData.ContainsKey(npc2.Name) &&
                        (Config.RoommateKisses || !npc1.getSpouse().friendshipData[npc1.Name].RoommateMarriage) && (Config.RoommateKisses || !npc1.getSpouse().friendshipData[npc2.Name].RoommateMarriage) &&
                        npc1.getSpouse().getFriendshipHeartLevelForNPC(npc1.Name) >= Config.MinHeartsForMarriageKiss && npc1.getSpouse().getFriendshipHeartLevelForNPC(npc2.Name) >= Config.MinHeartsForMarriageKiss &&
                        (Config.AllowRelativesToKiss || !Misc.AreNPCsRelated(npc1.Name, npc2.Name));

                    // check if spouses
                    if (!npcMarriageKiss && !npcRelatedHug && !playerSpouseKiss && !npcRoommateHug)
                        continue;

                    float distance = Vector2.Distance(npc1.position, npc2.position);
                    if (
                        distance < Config.MaxDistanceToKiss
                        && !npc1.isSleeping.Value
                        && !npc2.isSleeping.Value
                        && ModEntry.myRand.NextDouble() < Config.SpouseKissChance0to1
                    )
                    {
                        Monitor.Log($"{npc1.Name} and {npc2.Name} are marriage kissing: {npcMarriageKiss}, related hugging: {npcRelatedHug}, player spouse kissing: {playerSpouseKiss}");

                        lastKissed[npc1.Name] = elapsedSeconds;
                        lastKissed[npc2.Name] = elapsedSeconds;

                        Vector2 npc1pos = npc1.position;
                        Vector2 npc2pos = npc2.position;
                        int npc1face = npc1.facingDirection;
                        int npc2face = npc1.facingDirection;
                        Vector2 midpoint = new Vector2((npc1.position.X + npc2.position.X) / 2, (npc1.position.Y + npc2.position.Y) / 2);

                        PerformEmbrace(npc1, midpoint, npc2.Name);
                        PerformEmbrace(npc2, midpoint, npc1.Name);

                        if (playerSpouseKiss || npcMarriageKiss)
                        {
                            if (Config.CustomKissSound.Length > 0 && kissEffect != null)
                            {
                                float playerDistance = 1f / ((Vector2.Distance(midpoint, Game1.player.position) / 256) + 1);
                                kissEffect.Play(playerDistance * Game1.options.soundVolumeLevel, 0, 0);
                            }
                            else
                            {
                                Game1.currentLocation.playSound("dwop", NetAudio.SoundContext.NPC);
                            }
                            Misc.ShowHeart(npc1);
                            Misc.ShowHeart(npc2);

                        }
                        else
                        {
                            if (Config.CustomHugSound.Length > 0 && hugEffect != null)
                            {
                                float playerDistance = 1f / ((Vector2.Distance(midpoint, Game1.player.position) / 256) + 1);
                                hugEffect.Play(playerDistance * Game1.options.soundVolumeLevel, 0, 0);
                            }
                            Misc.ShowSmiley(npc1);
                            Misc.ShowSmiley(npc2);
                        }

                        DelayedAction action = new DelayedAction(1000);
                        var t = Task.Run(async delegate
                        {
                            await Task.Delay(TimeSpan.FromSeconds(1f));
                            npc1.position.Value = npc1pos;
                            npc2.position.Value = npc2pos;
                            npc1.FacingDirection = npc1face;
                            npc2.FacingDirection = npc2face;
                            npc1.Sprite.UpdateSourceRect();
                            npc2.Sprite.UpdateSourceRect();
                            return;
                        });
                    }
                }
            }
        }

19 View Source File : ExecutionContext.cs
License : MIT License
Project Creator : actions

public void ForceTaskComplete()
        {
            Trace.Info("Force finish current task in 5 sec.");
            Task.Run(async () =>
            {
                await Task.Delay(TimeSpan.FromSeconds(5));
                _forceCompleted?.TrySetResult(1);
            });
        }

19 View Source File : AElfKeyStore.cs
License : MIT License
Project Creator : AElfProject

public async Task<ECKeyPair> ReadKeyPairAsync(string address, string preplacedword)
        {
            try
            {
                var keyFilePath = GetKeyFileFullPath(address);
                var privateKey = await Task.Run(() =>
                {
                    using (var textReader = File.OpenText(keyFilePath))
                    {
                        var json = textReader.ReadToEnd();
                        return _keyStoreService.DecryptKeyStoreFromJson(preplacedword, json);
                    }
                });

                return CryptoHelper.FromPrivateKey(privateKey);
            }
            catch (FileNotFoundException ex)
            {
                throw new KeyStoreNotFoundException("Keystore file not found.", ex);
            }
            catch (DirectoryNotFoundException ex)
            {
                throw new KeyStoreNotFoundException("Invalid keystore path.", ex);
            }
            catch (DecryptionException ex)
            {
                throw new InvalidPreplacedwordException("Invalid preplacedword.", ex);
            }
        }

19 View Source File : Repository.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public virtual async Task<IQueryable<TEnreplacedy>> GetAll()
        {
            return await Task.Run(() => {
                return _dbSet;
            });
        }

19 View Source File : AssetLoader.cs
License : GNU General Public License v3.0
Project Creator : affederaffe

private async Task<GameObject> CreateHeartAsync()
        {
            (Vector3[] vertices, int[] triangles) = await Task.Run(() => ParseMesh("CustomFloorPlugin.replacedets.Heart.mesh"));
            Mesh mesh = new()
            {
                vertices = vertices,
                triangles = triangles
            };

            GameObject heart = new("<3");
            heart.SetActive(false);
            heart.AddComponent<MeshRenderer>();
            MeshFilter meshFilter = heart.AddComponent<MeshFilter>();
            meshFilter.mesh = mesh;
            heart.transform.localPosition = new Vector3(-8f, 25f, 26f);
            heart.transform.localRotation = Quaternion.Euler(-100f, 90f, 90f);
            heart.transform.localScale = new Vector3(25f, 25f, 25f);
            TubeLight tubeLight = heart.AddComponent<TubeLight>();
            tubeLight.color = Color.magenta;
            tubeLight.PlatformEnabled(_container);
            return heart;
        }

19 View Source File : FileLoggerProvider.cs
License : MIT License
Project Creator : adams85

private bool TryDisposeAsync(bool completeProcessorOnThreadPool, out Task completeProcessorTask)
        {
            lock (_loggers)
                if (!_isDisposed)
                {
                    _settingsChangeToken?.Dispose();

                    completeProcessorTask =
                        completeProcessorOnThreadPool ?
                        Task.Run(() => Processor.CompleteAsync()) :
                        Processor.CompleteAsync();

                    DisposeCore();

                    _isDisposed = true;
                    return true;
                }

            completeProcessorTask = null;
            return false;
        }

19 View Source File : ConnectionManager.cs
License : GNU General Public License v3.0
Project Creator : affederaffe

private void OnSongCoreEvent(bool usePlatform, string? name, string? hash, IPreviewBeatmapLevel _1)
        {
            // No platform is requested, abort
            if (!usePlatform)
            {
                _platformManager.APIRequestedPlatform = null;
                return;
            }

            // Check if the requested platform is already downloaded
            if (_platformManager.AllPlatforms.TryGetFirst(x => x.platHash == hash || x.platName == name, out CustomPlatform platform))
            {
                _platformManager.APIRequestedPlatform = platform;
                return;
            }

            string url = hash is not null ? $"https://modelsaber.com/api/v2/get.php?type=platform&filter=hash:{hash}"
                : name is not null ? $"https://modelsaber.com/api/v2/get.php?type=platform&filter=name:{name}"
                : throw new ArgumentNullException($"{nameof(hash)}, {nameof(name)}", "Invalid platform request");

            Task.Run(() => DownloadPlatform(url, _cancellationTokenSource.Token));
        }

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

static void Main(string[] args)
        {
            RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,asyncPipeline=true,preheat=100,poolsize=100"));
            cli.Set("TestMGet_null1", "");
            RedisHelper.Set("TestMGet_null1", "");
            sedb.StringSet("TestMGet_string1", String);
            ThreadPool.SetMinThreads(10001, 10001);
            Stopwatch sw = new Stopwatch();
            var tasks = new List<Task>();
            var results = new ConcurrentQueue<string>();

            cli.FlushDb();
            while (results.TryDequeue(out var del)) ;
            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                sedb.StringSet(tmp, String);
                var val = sedb.StringGet(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("StackExchange(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    sedb.StringSet(tmp, String);
                    var val = sedb.StringGet(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchange(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                cli.Set(tmp, String);
                var val = cli.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("FreeRedis(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    cli.Set(tmp, String);
                    var val = cli.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("FreeRedis(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await cli.SetAsync(tmp, String);
                    var val = await cli.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("FreeRedisAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            //FreeRedis.Internal.AsyncRedisSocket.sb.Clear();
            //FreeRedis.Internal.AsyncRedisSocket.sw.Start();
            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await cli.SetAsync(tmp, String);
                    var val = await cli.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            //var sbstr = FreeRedis.Internal.AsyncRedisSocket.sb.ToString()
            //sbstr = sbstr + sbstr.Split("\r\n").Length + "条消息 ;
            Console.WriteLine("FreeRedisAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            using (var pipe = cli.StartPipe())
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    pipe.Set(tmp, String);
                    var val = pipe.Get(tmp);
                }
                var vals = pipe.EndPipe();
                for (var a = 1; a < 200000; a += 2)
                {
                    var val = vals[a].ToString();
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }
            sw.Stop();
            Console.WriteLine("FreeRedisPipeline(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //    cli.Call(new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String));
            //sw.Stop();
            //Console.WriteLine("FreeRedis2: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //{
            //    using (var rds = cli.GetTestRedisSocket())
            //    {
            //        var cmd = new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String);
            //        rds.Write(cmd);
            //        cmd.Read<string>();
            //    }
            //}
            //sw.Stop();
            //Console.WriteLine("FreeRedis4: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                RedisHelper.Set(tmp, String);
                var val = RedisHelper.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("CSRedisCore(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    RedisHelper.Set(tmp, String);
                    var val = RedisHelper.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCore(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    //if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();
        }

19 View Source File : CustomBatchFixAllProvider.cs
License : Apache License 2.0
Project Creator : agoda-com

public virtual async Task<Solution> TryMergeFixesAsync(Solution oldSolution, IEnumerable<CodeAction> codeActions, CancellationToken cancellationToken)
        {
            var changedDoreplacedentsMap = new Dictionary<DoreplacedentId, Doreplacedent>();
            Dictionary<DoreplacedentId, List<Doreplacedent>> doreplacedentsToMergeMap = null;

            foreach (var codeAction in codeActions)
            {
                cancellationToken.ThrowIfCancellationRequested();

                // TODO: Parallelize GetChangedSolutionInternalAsync for codeActions
                var operations = await codeAction.GetPreviewOperationsAsync(cancellationToken).ConfigureAwait(false);
                ApplyChangesOperation singleApplyChangesOperation = null;
                foreach (var operation in operations)
                {
                    var applyChangesOperation = operation as ApplyChangesOperation;
                    if (applyChangesOperation == null)
                    {
                        continue;
                    }

                    if (singleApplyChangesOperation != null)
                    {
                        // Already had an ApplyChangesOperation; only one is supported.
                        singleApplyChangesOperation = null;
                        break;
                    }

                    singleApplyChangesOperation = applyChangesOperation;
                }

                if (singleApplyChangesOperation == null)
                {
                    continue;
                }

                var changedSolution = singleApplyChangesOperation.ChangedSolution;
                var solutionChanges = changedSolution.GetChanges(oldSolution);

                // TODO: Handle added/removed doreplacedents
                // TODO: Handle changed/added/removed additional doreplacedents
                var doreplacedentIdsWithChanges = solutionChanges
                    .GetProjectChanges()
                    .SelectMany(p => p.GetChangedDoreplacedents());

                foreach (var doreplacedentId in doreplacedentIdsWithChanges)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    var doreplacedent = changedSolution.GetDoreplacedent(doreplacedentId);

                    Doreplacedent existingDoreplacedent;
                    if (changedDoreplacedentsMap.TryGetValue(doreplacedentId, out existingDoreplacedent))
                    {
                        if (existingDoreplacedent != null)
                        {
                            changedDoreplacedentsMap[doreplacedentId] = null;
                            var doreplacedentsToMerge = new List<Doreplacedent>();
                            doreplacedentsToMerge.Add(existingDoreplacedent);
                            doreplacedentsToMerge.Add(doreplacedent);
                            doreplacedentsToMergeMap = doreplacedentsToMergeMap ?? new Dictionary<DoreplacedentId, List<Doreplacedent>>();
                            doreplacedentsToMergeMap[doreplacedentId] = doreplacedentsToMerge;
                        }
                        else
                        {
                            doreplacedentsToMergeMap[doreplacedentId].Add(doreplacedent);
                        }
                    }
                    else
                    {
                        changedDoreplacedentsMap[doreplacedentId] = doreplacedent;
                    }
                }
            }

            var currentSolution = oldSolution;
            foreach (var kvp in changedDoreplacedentsMap)
            {
                cancellationToken.ThrowIfCancellationRequested();
                var doreplacedent = kvp.Value;
                if (doreplacedent != null)
                {
                    var doreplacedentText = await doreplacedent.GetTextAsync(cancellationToken).ConfigureAwait(false);
                    currentSolution = currentSolution.WithDoreplacedentText(kvp.Key, doreplacedentText);
                }
            }

            if (doreplacedentsToMergeMap != null)
            {
                var mergedDoreplacedents = new ConcurrentDictionary<DoreplacedentId, SourceText>();
                var doreplacedentsToMergeArray = doreplacedentsToMergeMap.ToImmutableArray();
                var mergeTasks = new Task[doreplacedentsToMergeArray.Length];
                for (var i = 0; i < doreplacedentsToMergeArray.Length; i++)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    var kvp = doreplacedentsToMergeArray[i];
                    var doreplacedentId = kvp.Key;
                    var doreplacedentsToMerge = kvp.Value;
                    var oldDoreplacedent = oldSolution.GetDoreplacedent(doreplacedentId);

                    mergeTasks[i] = Task.Run(async () =>
                    {
                        var appliedChanges = (await doreplacedentsToMerge[0].GetTextChangesAsync(oldDoreplacedent, cancellationToken).ConfigureAwait(false)).ToList();

                        foreach (var doreplacedent in doreplacedentsToMerge.Skip(1))
                        {
                            cancellationToken.ThrowIfCancellationRequested();
                            appliedChanges = await TryAddDoreplacedentMergeChangesAsync(
                                oldDoreplacedent,
                                doreplacedent,
                                appliedChanges,
                                cancellationToken).ConfigureAwait(false);
                        }

                        var oldText = await oldDoreplacedent.GetTextAsync(cancellationToken).ConfigureAwait(false);
                        var newText = oldText.WithChanges(appliedChanges);
                        mergedDoreplacedents.TryAdd(doreplacedentId, newText);
                    });
                }

                await Task.WhenAll(mergeTasks).ConfigureAwait(false);

                foreach (var kvp in mergedDoreplacedents)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    currentSolution = currentSolution.WithDoreplacedentText(kvp.Key, kvp.Value);
                }
            }

            return currentSolution;
        }

19 View Source File : SharkControl.razor.cs
License : MIT License
Project Creator : ADefWebserver

public async ValueTask CreateScene()
        {            
            var canvas = await Canvas.GetElementById(
                "game-window"
            );
            var engine = await Engine.NewEngine(
                canvas,
                true
            );

            var scene = await Scene.NewScene(
                engine
            );
            var light0 = await PointLight.NewPointLight(
                "Omni",
                await Vector3.NewVector3(
                    0,
                    100,
                    8
                ),
                scene
            );
            var light1 = await HemisphericLight.NewHemisphericLight(
                "HemisphericLight",
                await Vector3.NewVector3(
                    0,
                    100,
                    8
                ),
                scene
            );

            var Player = await SceneLoader.ImportMesh(
                null,
                "replacedets/",
                "Shark.glb",
                scene,
                new ActionCallback<AbstractMesh[], IParticleSystem[], Skeleton[], AnimationGroup[], TransformNode[], Geometry[], Light[]>(async (arg1, arg2, arg3, arg4, arg5, arg6, arg7) =>
                {
                    foreach (var animation in arg4)
                    {
                        await animation.stop();
                        _animationMap.Add(await animation.get_name(), animation);
                    }

                    if (_animationMap.Count > 0)
                    {
                        _runningAnimation = _animationMap.First().Value;
                        await _runningAnimation.start(true);
                    }
                })
            );

            var camera = await ArcRotateCamera.NewArcRotateCamera(
                "ArcRotateCamera",
                (decimal)(System.Math.PI / 2),
                (decimal)(System.Math.PI / 4),
                0,
                await Vector3.NewVector3(0, 1, 0),
                scene
            );

            // This positions the camera
            await camera.setPosition(await Vector3.NewVector3(30, 10, -30));

            await camera.set_lowerRadiusLimit(2);
            await camera.set_upperRadiusLimit(100);
            await camera.set_wheelDeltaPercentage(0.01m);

            await scene.set_activeCamera(camera);

            await camera.attachControl(                
                false
            );

            await engine.runRenderLoop(new ActionCallback(
                            () => Task.Run(() => scene.render(true, false))
                        ));

            _engine = engine;
        }

19 View Source File : UserOnlyStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public async override Task<IList<TUser>> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            replacedertNotNull(claim, nameof(claim));

            var result = await _db.HashGetAllAsync(UserClaimsKeyPrefix + claim.Type)
                .ConfigureAwait(false);

            var users = new ConcurrentBag<TUser>();
            var taskList = new List<Task>(result.Length);
            foreach (var uc in result)
            {
                taskList.Add(Task.Run(async () => {
                    var user = await FindByIdAsync(uc.Name, cancellationToken)
                        .ConfigureAwait(false);
                    if (user != null)
                    {
                        users.Add(user);
                    }
                }));
            }

            await Task.WhenAll(taskList.ToArray())
                .ConfigureAwait(false);

            return users.ToList();
        }

19 View Source File : MixedRealityToolkitFiles.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static void RefreshFolders()
        {
            string path = Application.dataPath;
            searchForFoldersTask = Task.Run(() => SearchForFoldersAsync(path));
        }

19 View Source File : AzureBlobXmlRepository.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public IReadOnlyCollection<XElement> GetAllElements()
        {
            // Shunt the work onto a ThreadPool thread so that it's independent of any
            // existing sync context or other potentially deadlock-causing items.

            var elements = Task.Run(() => GetAllElementsAsync()).GetAwaiter().GetResult();
            return new ReadOnlyCollection<XElement>(elements);
        }

19 View Source File : JobDispatcher_HandleNextJobAsync_Test.cs
License : MIT License
Project Creator : AdemCatamak

[Theory]
        [InlineData(1, 100)]
        [InlineData(4, 100)]
        [InlineData(8, 100)]
        [InlineData(1, 300)]
        [InlineData(4, 300)]
        [InlineData(8, 300)]
        [InlineData(12, 300)]
        [InlineData(16, 300)]
        [InlineData(1, 1000)]
        [InlineData(4, 1000)]
        [InlineData(8, 1000)]
        [InlineData(12, 1000)]
        [InlineData(16, 1000)]
        public void When_JobHandledCalledWithParallel__InitialJobCountAndJobExecutionCountShouldBeEqual(int parallelJobCount, int initialJobCount)
        {
            List<Task> addTasks = new List<Task>();
            for (var i = 0; i < initialJobCount; i++)
            {
                DummyMessage dummyMessage = new DummyMessage
                {
                    Guid = Guid.NewGuid()
                };
                var task = _messageStorageClient.AddMessageAsync(dummyMessage);
                addTasks.Add(task);
            }

            Task.WaitAll(addTasks.ToArray());

            List<Task> jobProcessorTasks = new List<Task>();
            var actualExecutedJobCount = 0;
            for (var i = 0; i < parallelJobCount; i++)
            {
                Task task = Task.Run(async () =>
                                     {
                                         bool jobHandled;
                                         do
                                         {
                                             jobHandled = await _jobDispatcher.HandleNextJobAsync();
                                             if (jobHandled)
                                             {
                                                 Interlocked.Increment(ref actualExecutedJobCount);
                                             }
                                         } while (jobHandled);
                                     }
                                    );
                jobProcessorTasks.Add(task);
            }

            Task.WaitAll(jobProcessorTasks.ToArray());

            string message = $"Parallel Job Count : {parallelJobCount}{Environment.NewLine}" +
                             $"Expected Executed Job Count : {initialJobCount}{Environment.NewLine}" +
                             $"Actual Executed Job Count : {actualExecutedJobCount}";
            replacedert.Equal(initialJobCount, actualExecutedJobCount);
            _output.WriteLine(message);
        }

19 View Source File : RestClient.cs
License : MIT License
Project Creator : Aiko-IT-Systems

private void FailInitialRateLimitTest(BaseRestRequest request, TaskCompletionSource<bool> ratelimitTcs, bool resetToInitial = false)
        {
            if (ratelimitTcs == null && !resetToInitial)
                return;

            var bucket = request.RateLimitBucket;

            bucket._limitValid = false;
            bucket._limitTestFinished = null;
            bucket._limitTesting = 0;

            //Reset to initial values.
            if (resetToInitial)
            {
                this.UpdateHashCaches(request, bucket);
                bucket.Maximum = 0;
                bucket._remaining = 0;
                return;
            }

            // no need to wait on all the potentially waiting tasks
            _ = Task.Run(() => ratelimitTcs.TrySetResult(false));
        }

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

public async Task<RegisteredUser> RegisterUserAsync(RegistrationRequest request)
        {
            return await Task.Run(() => RegisterUser(request));
        }

19 View Source File : AsyncManualResetEvent.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public Task SetAsync()
            => Task.Run(() => this._resetTcs.TrySetResult(true));

19 View Source File : ItemFieldsToFlow.cs
License : MIT License
Project Creator : adoprog

public void Process(WorkflowPipelineArgs args)
    {
      Item dataItem = args.DataItem;
      if (args.DataItem == null)
      {
        return;
      }

      var url = args.ProcessorItem.InnerItem[HttpPostUrlField];
      var contextSite = args.ProcessorItem.InnerItem[ContextSiteField];
      var requestor = new Requestor();
      if (dataItem != null && dataItem.Parent != null)
      {
        var json = GetFieldsJson(dataItem, contextSite);
        Task.Run(() => requestor.PostRequest((string)url, json));
      }
    }

19 View Source File : AscReader.cs
License : MIT License
Project Creator : ABTSoftware

public static async Task<AscData> ReadResourceToAscData(
            string resourceName, Func<float, Color> colorMapFunction, Action<int> reportProgress = null)
        {
            var result = await Task.Run(() =>
            {
                var asm = replacedembly.GetExecutingreplacedembly();
                var resource = asm.GetManifestResourceNames()
                    .Single(x => x.Contains(resourceName));

                using (var stream = asm.GetManifestResourceStream(resource))
                using (var gz = new GZipStream(stream, CompressionMode.Decompress))
                using (var streamReader = new StreamReader(gz))
                {
                    return ReadFromStream(streamReader, colorMapFunction, reportProgress);
                }
            });

            return result;
        }

19 View Source File : SpamContext.cs
License : MIT License
Project Creator : 0x0ade

public bool Add() {
                lock (Spam.Timeouts) {
                    if (Count < Spam.Chat.Settings.SpamCountMax) {
                        Count++;

                        Task.Run(async () => {
                            await Task.Delay(TimeSpan.FromSeconds(Spam.Chat.Settings.SpamTimeoutAdd));
                            lock (Spam.Timeouts) {
                                if (Unspammed)
                                    return;
                                Count--;
                                if ((!Spammed || Timeout.Ticks <= 0) && Count <= 0)
                                    Spam.Timeouts.Remove(Text);
                            }
                        });
                    }

                    if (Spammed || Count >= Spam.Chat.Settings.SpamCount) {
                        if (!Spammed)
                            Start = DateTime.UtcNow;
                        Spammed = true;
                        Task.Run(async () => {
                            TimeSpan timeout = Timeout;
                            if (timeout.Ticks > 0)
                                await Task.Delay(timeout);
                            lock (Spam.Timeouts) {
                                if (Unspammed)
                                    return;
                                if (Count <= 0) {
                                    Unspammed = true;
                                    Spam.Timeouts.Remove(Text);
                                }
                            }
                        });
                        return true;
                    }

                    return false;
                }
            }

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

public async Task DeleteFileAsync(string fileId)
        {
            replacedertIdenreplacedyProvided(); // Quota is affected
            var filePath = GetTargetFilePath(fileId);
            var fileInfo = await Task.Run(() => new FileInfo(filePath));
            var fileSize = fileInfo.Length;
            await Task.Run(() => File.Delete(filePath));
            if (_owner != null)
            {
                var lockEntry = ServerContext.ServiceTable[_owner].UserLock;
                // Decrease user storage usage
                await lockEntry.ObtainExclusiveWriteAsync();
                var userManager = new WebUserManager(ServerContext);
                var ownerData = await userManager.FindUserByUsernameAsync(_owner);
                var prevStorageUsage = ownerData.StorageUsage;
                ownerData.StorageUsage -= fileSize;
                await userManager.UpdateUserInDatabaseAsync(ownerData);
                lockEntry.ReleaseExclusiveWrite();
            }
        }

19 View Source File : Repository.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public virtual async Task<IQueryable<TEnreplacedy>> GetAll(Expression<Func<TEnreplacedy, bool>> where)
        {
            return await Task.Run(() => {
                return _dbSet.Where(where);
            });
        }

19 View Source File : ProcessInvoker.cs
License : MIT License
Project Creator : actions

private void ProcessExitedHandler(object sender, EventArgs e)
        {
            if ((_proc.StartInfo.RedirectStandardError || _proc.StartInfo.RedirectStandardOutput) && _asyncStreamReaderCount != 0)
            {
                _waitingOnStreams = true;

                Task.Run(async () =>
                {
                    // Wait 5 seconds and then Cancel/Kill process tree
                    await Task.Delay(TimeSpan.FromSeconds(5));
                    KillProcessTree();
                    _processExitedCompletionSource.TrySetResult(true);
                    _processStandardInWriteCancellationTokenSource.Cancel();
                });
            }
            else
            {
                _processExitedCompletionSource.TrySetResult(true);
                _processStandardInWriteCancellationTokenSource.Cancel();
            }
        }

19 View Source File : Kissing.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void TrySpousesKiss()
        {
            GameLocation location = Game1.currentLocation;

            if (location == null || !ReferenceEquals(location.GetType(), typeof(FarmHouse)))
                return;

            Farmer owner = (location as FarmHouse).owner;

            lastKissTime++;

            if (location == null || location.characters == null)
                return;

            List<NPC> list = location.characters.ToList();

            Misc.ShuffleList(ref list);

            foreach (NPC npc1 in list)
            {
                if (!owner.friendshipData.ContainsKey(npc1.Name))
                    continue;

                if (!ModEntry.config.RoommateRomance && owner.friendshipData[npc1.Name].RoommateMarriage)
                {
                    continue;
                }


                foreach (NPC npc2 in list)
                {
                    if (!owner.friendshipData.ContainsKey(npc2.Name))
                        continue;

                    if (npc1.Name == npc2.Name || (!ModEntry.config.RoommateRomance && owner.friendshipData[npc2.Name].RoommateMarriage))
                    {
                        continue;
                    }

                    if (lastKissTime >= ModEntry.config.MinSpouseKissInterval)
                        kissingSpouses.Clear();


                    float distance = Vector2.Distance(npc1.position, npc2.position);
                    if (
                        npc1.getSpouse() != null && npc2.getSpouse() != null  
                        && npc1.getSpouse().Name == npc2.getSpouse().Name 
                        && distance < ModEntry.config.MaxDistanceToKiss 
                        && !kissingSpouses.Contains(npc1.Name) 
                        && !kissingSpouses.Contains(npc2.Name) 
                        && !npc1.isSleeping 
                        && !npc2.isSleeping 
                        && owner.getFriendshipHeartLevelForNPC(npc1.Name) >= ModEntry.config.MinHeartsForKiss
                        && owner.getFriendshipHeartLevelForNPC(npc2.Name) >= ModEntry.config.MinHeartsForKiss
                        && lastKissTime > ModEntry.config.MinSpouseKissInterval 
                        && ModEntry.myRand.NextDouble() < ModEntry.config.SpouseKissChance
                        && (!ModEntry.config.PreventRelativesFromKissing || !Misc.AreSpousesRelated(npc1.Name, npc2.Name))
                    )
                    {
                        kissingSpouses.Add(npc1.Name);
                        kissingSpouses.Add(npc2.Name);
                        ModEntry.PMonitor.Log("spouses kissing"); 
                        lastKissTime = 0;
                        Vector2 npc1pos = npc1.position;
                        Vector2 npc2pos = npc2.position;
                        int npc1face = npc1.facingDirection;
                        int npc2face = npc1.facingDirection;
                        Vector2 midpoint = new Vector2((npc1.position.X + npc2.position.X) / 2, (npc1.position.Y + npc2.position.Y) / 2);
                        PerformKiss(npc1, midpoint, npc2.Name);
                        PerformKiss(npc2, midpoint, npc1.Name);
                        DelayedAction action = new DelayedAction(1000);
                        var t = Task.Run(async delegate
                        {
                            await Task.Delay(TimeSpan.FromSeconds(1));
                            npc1.position.Value = npc1pos;
                            npc2.position.Value = npc2pos;
                            npc1.FacingDirection = npc1face;
                            npc2.FacingDirection = npc2face;
                            return;
                        });
                    }
                }
            }
        }

See More Examples