System.Threading.Tasks.Task.WaitAll(params System.Threading.Tasks.Task[])

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

721 Examples 7

19 View Source File : LoadTestService.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

public void ExecuteNumberOfTimes(int numberOfProcesses, int pauseBetweenStartSeconds, int timesToBeExecuted, Action testBody)
        {
            if (numberOfProcesses <= 0)
            {
                throw new ArgumentException($"Number of processes should be a positive number.");
            }

            if (pauseBetweenStartSeconds < 0)
            {
                throw new ArgumentException($"Pause between start of processes should be a positive number.");
            }

            if (timesToBeExecuted < 0)
            {
                throw new ArgumentException($"Times to be executed should be a positive number.");
            }

            for (int i = 0; i < timesToBeExecuted; i++)
            {
                var loadTasks = CreateTestTasks(numberOfProcesses, pauseBetweenStartSeconds, testBody);
                Task.WaitAll(loadTasks.ToArray());
            }
        }

19 View Source File : AWSXRayRecorderTests.cs
License : Apache License 2.0
Project Creator : aws

[TestMethod]
        public void TestAsyncCreateTwoSubsegment()
        {
            _recorder.BeginSegment("parent", TraceId);
            Segment parent = (Segment)AWSXRayRecorder.Instance.TraceContext.GetEnreplacedy();

            Subsegment child1 = null;
            Subsegment child2 = null;

            Task task1 = Task.Run(async () =>
            {
                _recorder.BeginSubsegment("child1");
                await Task.Delay(1000);   // Ensure task1 will not complete when task1 is running
                child1 = (Subsegment)AWSXRayRecorder.Instance.TraceContext.GetEnreplacedy();
                _recorder.EndSubsegment();
            });

            Task task2 = Task.Run(() =>
            {
                _recorder.BeginSubsegment("child2");
                child2 = (Subsegment)AWSXRayRecorder.Instance.TraceContext.GetEnreplacedy();
                _recorder.EndSubsegment();
            });

            Task.WaitAll(task1, task2);

            _recorder.EndSegment();

            replacedert.IsNotNull(child1);
            replacedert.IsNotNull(child2);
            replacedert.ReferenceEquals(parent, child1.Parent);
            replacedert.ReferenceEquals(parent, child2.Parent);
            replacedert.IsTrue(parent.Subsegments.Contains(child1));
            replacedert.IsTrue(parent.Subsegments.Contains(child2));
        }

19 View Source File : Server.cs
License : MIT License
Project Creator : AmazingDM

public int Test()
        {
            try
            {
                var destination = DNS.Lookup(Hostname);
                if (destination == null)
                    return Delay = -2;

                var list = new Task<int>[3];
                for (var i = 0; i < 3; i++)
                    list[i] = Task.Run(async () =>
                    {
                        try
                        {
                            return Global.Settings.ServerTCPing ? await Utils.Utils.TCPingAsync(destination, Port) : await Utils.Utils.ICMPing(destination, Port);
                        }
                        catch (Exception)
                        {
                            return -4;
                        }
                    });

                Task.WaitAll(list[0], list[1], list[2]);

                var min = Math.Min(list[0].Result, list[1].Result);
                min = Math.Min(min, list[2].Result);
                return Delay = min;
            }
            catch (Exception)
            {
                return Delay = -4;
            }
        }

19 View Source File : TestUtils.cs
License : MIT License
Project Creator : asc-community

public void Run(int iterCount = 1, int threadCount = 4)
        {
            var tasks = new Task[threadCount];
            for (var i = 0; i < threadCount; i++)
                tasks[i] = Task.Run(
                    () =>
                    {
                        var iterCountLocal = iterCount;
                        for (var j = 0; j < iterCountLocal; j++)
                            action(i);
                    }
                );
            Task.WaitAll(tasks);
        }

19 View Source File : SharlayanHelper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private void GarbageCombatantsDictionary()
        {
            Task.WaitAll(
                Task.Run(() =>
                {
                    var dic = this.CombatantsDictionary;
                    var keys = dic
                        .Where(x => (DateTime.Now - x.Value.Timestamp) >= TimeSpan.FromMinutes(2.9))
                        .Select(x => x.Key)
                        .ToArray();

                    foreach (var key in keys)
                    {
                        dic.Remove(key);
                    }
                }),
                Task.Run(() =>
                {
                    var dic = this.NPCCombatantsDictionary;
                    var keys = dic
                        .Where(x => (DateTime.Now - x.Value.Timestamp) >= TimeSpan.FromMinutes(2.9))
                        .Select(x => x.Key)
                        .ToArray();

                    foreach (var key in keys)
                    {
                        dic.Remove(key);
                    }
                }));
        }

19 View Source File : Parser.cs
License : MIT License
Project Creator : alexanderkyte

public Type
		Emit (string outputName, string outputFilePath)
		{
			// Make sure we are finished parsing.
			Task.WaitAll (work);

			replacedemblyName aName = new replacedemblyName (String.Format ("{0}Proxy", outputName));
			replacedemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicreplacedembly (aName, replacedemblyBuilderAccess.RunAndSave);

			// FIXME: always want to provide debug info or not?
			ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, outputFilePath);

			TypeBuilder tb = mb.DefineType (outputName, TypeAttributes.Public, typeof (WebreplacedemblyModule));

			var constructor = tb.DefineConstructor (MethodAttributes.Public, CallingConventions.Standard, new Type []{});
			var ctor_gen = constructor.GetILGenerator();

			// the constructor gets the "this" pointer
			ctor_gen.Emit(OpCodes.Ldarg_0);

			// Next arg is the size
			if (mem != null)
				ctor_gen.Emit(OpCodes.Ldc_I4, mem.limit.min);
			else
				ctor_gen.Emit(OpCodes.Ldc_I4_0);

			ctor_gen.Emit(OpCodes.Call, typeof (WebreplacedemblyModule).GetConstructor (new Type[] { typeof (int) }));
			ctor_gen.Emit(OpCodes.Ret);

			// Compute exports
			var export_table = new Dictionary<int, string> ();
			if (exports != null) {
				foreach (var exp in exports) {
					if (exp.kind == 0x0) // function export
						export_table [Convert.ToInt32 (exp.index)] = exp.name;
				}
			}

			// fixme: imports / exports?
			for (int i=0; i < exprs.Length; i++) {
				var fn = exprs [i];
				var type = types [fn_to_type [i]];
				string fn_name;
				if (export_table.ContainsKey (i))
					fn_name = export_table [i];
				else
					fn_name = String.Format ("Function{0}", i);
				var emitted = fn.Emit (type, tb, fn_name);
			}

			var goal = tb.CreateType ();

			if (outputFilePath != null)
				ab.Save (outputFilePath);

			return goal;
		}

19 View Source File : ValidatorTest.cs
License : MIT License
Project Creator : Avanade

[Test]
        public void Enreplacedy_ValueCachePerfAsync()
        {
            var tasks = new Task[10];
            for (int i = 0; i < 10; i++)
            {
                tasks[i] = Task.Run(() => InstantiateValidators());
            }

            Task.WaitAll(tasks);
        }

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 : RulesFileLoader.cs
License : Apache License 2.0
Project Creator : aws

public RootNodes Load()
        {
            var mainNamespaceFileTasks = new Task<NamespaceRecommendations>(() =>
            {
                NamespaceRecommendations rulesFile = new NamespaceRecommendations();
                if (!string.IsNullOrEmpty(_rulesFilesDir) && Directory.Exists(_rulesFilesDir))
                {
                    rulesFile = LoadNamespaceFile(_rulesFilesDir);
                }
                return rulesFile;
            });
            mainNamespaceFileTasks.Start();

            var mainFileTask = new Task<Rootobject>(() =>
            {
                Rootobject rules = new Rootobject();
                if (!string.IsNullOrEmpty(_rulesFilesDir) && Directory.Exists(_rulesFilesDir))
                {
                    rules = LoadRulesFiles(_rulesFilesDir);
                    if (rules.NameSpaces != null)
                    {
                        rules.NameSpaces = rules.NameSpaces.Where(n => _projectReferences.Contains(new Reference() { replacedembly = n.replacedembly, Namespace = [email protected] }) || (n.replacedembly == Constants.Project)).ToList();
                    }
                }
                return rules;
            });
            mainFileTask.Start();

            var overrideNamespaceFileTasks = new Task<NamespaceRecommendations>(() =>
            {
                NamespaceRecommendations rulesFile = new NamespaceRecommendations();
                if (!string.IsNullOrEmpty(_overrideFile) && Directory.Exists(_overrideFile))
                {
                    rulesFile = LoadNamespaceFile(_overrideFile);
                }
                return rulesFile;
            });
            overrideNamespaceFileTasks.Start();

            var overrideTask = new Task<Rootobject>(() =>
            {
                Rootobject rules = new Rootobject();
                if (!string.IsNullOrEmpty(_overrideFile) && Directory.Exists(_overrideFile))
                {
                    rules = LoadRulesFiles(_overrideFile);
                    if (rules.NameSpaces != null)
                    {
                        rules.NameSpaces = rules.NameSpaces.Where(n => _projectReferences.Contains(new Reference() { replacedembly = n.replacedembly, Namespace = [email protected] }) || (n.replacedembly == Constants.Project && [email protected] == Constants.Project)).ToList();
                    }
                }
                return rules;
            });
            overrideTask.Start();

            Task.WaitAll(mainNamespaceFileTasks, overrideNamespaceFileTasks, mainFileTask, overrideTask);

            RulesFileParser rulesFileParser = new RulesFileParser(mainNamespaceFileTasks.Result,
                overrideNamespaceFileTasks.Result,
                mainFileTask.Result,
                overrideTask.Result,
                _replacedembliesDir,
                _targetFramework
                );
            var rootNodes = rulesFileParser.Process();

            return rootNodes;
        }

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 : TilesConverterTests.cs
License : MIT License
Project Creator : arcplus

[Fact]
        public void Test_BatchTileset()
        {
            var folder = @"..\..\..\..\testreplacedets\BatchTests";
            replacedert.True(Directory.Exists(folder), "Input folder does not exist!");
            var outputDir = "BatchTests";
            var files = Directory.GetFiles(folder); // obj Files are zipped with mtl files
            foreach(var f in files)
            {
                var name = Path.GetFileNameWithoutExtension(f);
                var dir = Path.Combine(folder, name);
                Directory.CreateDirectory(dir);
                ExtractZipFile(f, String.Empty, dir);
            }
            var gisPosition = new GisPosition
            {
                Longitude = 0,
                Lareplacedude = 0,
                TransHeight = 0
            };
            var objFiles = Directory.GetFiles(folder, "*.obj", SearchOption.AllDirectories);
            var tasks = new Task<string>[objFiles.Length];
            for(var i = 0;i<objFiles.Length;i++)
            {
                var objFile = objFiles[i];
                var dd = Path.GetDirectoryName(objFile);
                
                var name = "Batched" + Path.GetFileNameWithoutExtension(dd);
                var outFolder = Path.Combine(outputDir, name);
                Directory.CreateDirectory(outFolder);
                tasks[i] = Task.Run(() => TilesConverter.WriteTilesetFile(objFile, outFolder, gisPosition));
            }
            Task.WaitAll(tasks);
            var strs = new List<string>();
            var tilesetListFile = Path.Combine(outputDir, "tileset.txt");
            foreach(var t in tasks)
            {
                var res = t.Result;
                var name = Path.GetFileNameWithoutExtension(res);
                var dir = Path.GetDirectoryName(res);
                var bName = Path.GetFileNameWithoutExtension(dir);
                strs.Add($"loadTileSet('{bName}', 'BatchedTest/{bName}/tileset.json');");
            }
            using (var sw = new StreamWriter(tilesetListFile, true, System.Text.Encoding.UTF8))
            {
                foreach(var s in strs)
                {
                    sw.WriteLine(s);
                }
                sw.Flush();
                sw.Close();
            }
        }

19 View Source File : TilesConverter.cs
License : MIT License
Project Creator : arcplus

internal static string MergeTilesets(string objFolder, string outputFolder, 
            GisPosition gisPosition, bool lod, bool writeChildTilesetJson, params ObjModel[] objModels)
        {
            var tasks = new Task<SingleTileset>[objModels.Length];
            var outputPath = GenerateBatchedPath(outputFolder);
            if (!Directory.Exists(outputPath)) Directory.CreateDirectory(outputPath);
            for (var i = 0; i < objModels.Length; i++)
            {
                var objFile = objModels[i];
                tasks[i] = Task.Run(() => WriteTileset(objFile, objFolder, outputPath, gisPosition));
            }
            Task.WaitAll(tasks);

            return MergeTilesets(outputFolder, gisPosition, lod, writeChildTilesetJson, tasks);
        }

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

[Fact]
        public void TryAdd_Mulreplacedhreads_WithDifferentData()
        {
            var chainId = 123;
            var initTarget = 1;
            var blockInfoCache = new ChainCacheEnreplacedy(chainId, initTarget);
            var i = 0;
            var taskList = new List<Task>();
            while (i < 5)
            {
                var j = i;
                var t = Task.Run(() => blockInfoCache.TryAdd(new SideChainBlockData
                {
                    Height = 2 * j + 1,
                    ChainId = chainId,
                    TransactionStatusMerkleTreeRoot = HashHelper.ComputeFrom((2 * j + 1).ToString())
                }));
                taskList.Add(t);
                i++;
            }

            Task.WaitAll(taskList.ToArray());
            replacedert.True(blockInfoCache.TargetChainHeight() == initTarget + 1);
        }

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : aspnet

public static void Main(string[] args)
        {
            Uri uri = new Uri("http://localhost:12345/small-immediate-syncwrite");
            HttpClient client = new HttpClient();
            List<Task> offloads = new List<Task>();

            for (int i = 0; i < 10; i++)
            {
                Task offload = Task.Run(async () =>
                    {
                        try
                        {
                            for (int j = 0; j < 100000; j++)
                            {
                                HttpResponseMessage response = await client.GetAsync(uri);
                                response.EnsureSuccessStatusCode();
                                response.Dispose();
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                    });
                offloads.Add(offload);
            }

            Task.WaitAll(offloads.ToArray());
        }

19 View Source File : SpeedtestHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust

private void RunRealPing()
        {
            int pid = -1;
            try
            {
                string msg = string.Empty;

                pid = _v2rayHandler.LoadV2rayConfigString(_config, _selecteds);
                if (pid < 0)
                {
                    _updateFunc(_selecteds[0], UIRes.I18N("OperationFailed"));
                    return;
                }

                //Thread.Sleep(5000);
                int httpPort = _config.GetLocalPort("speedtest");
                List<Task> tasks = new List<Task>();
                foreach (int itemIndex in _selecteds)
                {
                    if (_config.vmess[itemIndex].configType == (int)EConfigType.Custom)
                    {
                        continue;
                    }
                    tasks.Add(Task.Run(() =>
                    {
                        try
                        {
                            WebProxy webProxy = new WebProxy(Global.Loopback, httpPort + itemIndex);
                            int responseTime = -1;
                            string status = GetRealPingTime(_config.speedPingTestUrl, webProxy, out responseTime);
                            string output = Utils.IsNullOrEmpty(status) ? FormatOut(responseTime, "ms") : FormatOut(status, "");
                            _updateFunc(itemIndex, output);
                        }
                        catch (Exception ex)
                        {
                            Utils.SaveLog(ex.Message, ex);
                        }
                    }));
                    //Thread.Sleep(100);
                }
                Task.WaitAll(tasks.ToArray());
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
            }
            finally
            {
                if (pid > 0) _v2rayHandler.V2rayStopPid(pid);
            }
        }

19 View Source File : KeyValueCacheTest.cs
License : MIT License
Project Creator : Avanade

[Test]
        public void Concurrency()
        {
            Policy.CachePolicyManagerTest.TestSetUp();

            var l = new object();
            int i = 0;
            var mtc = new KeyValueCache<int, string>((key) => { lock (l) { i++; } TestContext.WriteLine($"GetValue {key} [{System.Threading.Thread.CurrentThread.ManagedThreadId}]"); System.Threading.Thread.Sleep(20); return key.ToString(); });

            // Set an execution context.
            var tasks = new Task[13];
            tasks[0] = Task.Run(() => Timer(0, 1, () => { replacedert.AreEqual(mtc[1], "1"); }));
            tasks[1] = Task.Run(() => Timer(1, 2, () => { replacedert.AreEqual(mtc[2], "2"); }));
            tasks[2] = Task.Run(() => Timer(2, 2, () => { replacedert.AreEqual(mtc[2], "2"); }));
            tasks[3] = Task.Run(() => Timer(3, 3, () => { replacedert.AreEqual(mtc[3], "3"); }));
            tasks[4] = Task.Run(() => Timer(4, 2, () => { replacedert.AreEqual(mtc[2], "2"); }));
            tasks[5] = Task.Run(() => Timer(5, 1, () => { replacedert.AreEqual(mtc[1], "1"); }));
            tasks[6] = Task.Run(() => Timer(6, 2, () => { replacedert.AreEqual(mtc[2], "2"); }));
            tasks[7] = Task.Run(() => Timer(7, 2, () => { replacedert.AreEqual(mtc[2], "2"); }));
            tasks[8] = Task.Run(() => Timer(8, 3, () => { replacedert.AreEqual(mtc[3], "3"); }));
            tasks[9] = Task.Run(() => Timer(9, 2, () => { replacedert.AreEqual(mtc[2], "2"); }));
            tasks[10] = Task.Run(() => Timer(10, 1, () => { replacedert.AreEqual(mtc[1], "1"); }));
            tasks[11] = Task.Run(() => Timer(11, 2, () => { replacedert.AreEqual(mtc[2], "2"); }));
            tasks[12] = Task.Run(() => Timer(12, 3, () => { replacedert.AreEqual(mtc[3], "3"); }));

            Task.WaitAll(tasks);

            replacedert.AreEqual(3, i);

            TestContext.WriteLine("Round 2");

            tasks = new Task[13];
            tasks[0] = Task.Run(() => Timer(0, 1, () => { replacedert.AreEqual(mtc[1], "1"); }));
            tasks[1] = Task.Run(() => Timer(1, 2, () => { replacedert.AreEqual(mtc[2], "2"); }));
            tasks[2] = Task.Run(() => Timer(2, 2, () => { replacedert.AreEqual(mtc[2], "2"); }));
            tasks[3] = Task.Run(() => Timer(3, 3, () => { replacedert.AreEqual(mtc[3], "3"); }));
            tasks[4] = Task.Run(() => Timer(4, 2, () => { replacedert.AreEqual(mtc[2], "2"); }));
            tasks[5] = Task.Run(() => Timer(5, 1, () => { replacedert.AreEqual(mtc[1], "1"); }));
            tasks[6] = Task.Run(() => Timer(6, 2, () => { replacedert.AreEqual(mtc[2], "2"); }));
            tasks[7] = Task.Run(() => Timer(7, 2, () => { replacedert.AreEqual(mtc[2], "2"); }));
            tasks[8] = Task.Run(() => Timer(8, 3, () => { replacedert.AreEqual(mtc[3], "3"); }));
            tasks[9] = Task.Run(() => Timer(9, 2, () => { replacedert.AreEqual(mtc[2], "2"); }));
            tasks[10] = Task.Run(() => Timer(10, 1, () => { replacedert.AreEqual(mtc[1], "1"); }));
            tasks[11] = Task.Run(() => Timer(11, 2, () => { replacedert.AreEqual(mtc[2], "2"); }));
            tasks[12] = Task.Run(() => Timer(12, 3, () => { replacedert.AreEqual(mtc[3], "3"); }));

            Task.WaitAll(tasks);

            replacedert.AreEqual(3, i);
        }

19 View Source File : EncodeVideo.cs
License : MIT License
Project Creator : Alkl58

public static void Encode()
        {
            // Main Encoding Function
            // Creates a new Thread Pool
            using (SemapreplacedSlim concurrencySemapreplaced = new SemapreplacedSlim(Worker_Count))
            {
                // Creates a tasks list
                List<Task> tasks = new List<Task>();
                // Iterates over all args in VideoChunks list
                foreach (var command in Global.Video_Chunks)
                {
                    concurrencySemapreplaced.Wait();
                    var task = Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            if (!SmallFunctions.Cancel.CancelAll)
                            {
                                // We need the index of the command in the array
                                var index = Array.FindIndex(Global.Video_Chunks, row => row.Contains(command));
                                // Logic for resume mode - skips already encoded files
                                if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf" + "_finished.log")) == false)
                                {
                                    // One Preplaced Encoding
                                    Process ffmpegProcess = new Process();
                                    ProcessStartInfo startInfo = new ProcessStartInfo
                                    {
                                        UseShellExecute = true,
                                        FileName = "cmd.exe",
                                        WorkingDirectory = Global.FFmpeg_Path
                                    };

                                    if (!Show_Terminal)
                                    {
                                        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                                    }

                                    string InputVideo = "";

                                    if (Splitting.split_type >= 1)
                                    {
                                        // FFmpeg Scene Detect or PySceneDetect
                                        InputVideo = " -i " + '\u0022' + Global.Video_Path + '\u0022' + " " + command;
                                    }
                                    else if (Splitting.split_type == 0)
                                    {
                                        // Chunk based splitting
                                        InputVideo = " -i " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", command) + '\u0022';
                                    }

                                    // Saves encoder progress to log file
                                    string ffmpeg_progress = " -an -progress " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Progress", "split" + index.ToString("D5") + "_progress.log") + '\u0022';

                                    string ffmpeg_input = InputVideo + " " + MainWindow.FilterCommand + Pixel_Format + " " + MainWindow.VSYNC + " ";

                                    // Process Exit Code
                                    int exit_code = 0;

                                    // Logic to skip first preplaced encoding if "_finished" log file exists
                                    if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log" + "_finished.log")) == false)
                                    {
                                        string encoderCMD = "";

                                        if (MainWindow.OnePreplaced)
                                        {
                                            // One Preplaced Encoding
                                            encoderCMD = " -y " + Final_Encoder_Command + " ";
                                            encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".webm") + '\u0022';
                                        }
                                        else
                                        {
                                            // Two Preplaced Encoding - First Preplaced
                                            encoderCMD = " -y " + Final_Encoder_Command + " -preplaced 1 -preplacedlogfile ";
                                            encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022' + " -f webm NUL";
                                        }

                                        startInfo.Arguments = "/C ffmpeg.exe " + ffmpeg_progress + ffmpeg_input + encoderCMD;

                                        Helpers.Logging("Encoding Video: " + startInfo.Arguments);
                                        ffmpegProcess.StartInfo = startInfo;
                                        ffmpegProcess.Start();

                                        // Sets the process priority
                                        if (!Process_Priority)
                                            ffmpegProcess.PriorityClreplaced = ProcessPriorityClreplaced.BelowNormal;

                                        // Get launched Process ID
                                        int temp_pid = ffmpegProcess.Id;

                                        // Add Process ID to Array, inorder to keep track / kill the instances
                                        Global.Launched_PIDs.Add(temp_pid);

                                        ffmpegProcess.WaitForExit();

                                        // Get Exit Code
                                        exit_code = ffmpegProcess.ExitCode;

                                        if (exit_code != 0)
                                            Helpers.Logging("Chunk " + command + " Failed with Exit Code: " + exit_code.ToString());

                                        // Remove PID from Array after Exit
                                        Global.Launched_PIDs.RemoveAll(i => i == temp_pid);

                                        if (MainWindow.OnePreplaced == false && SmallFunctions.Cancel.CancelAll == false && exit_code == 0)
                                        {
                                            // Writes log file if first preplaced is finished, to be able to skip them later if in resume mode
                                            Helpers.WriteToFileThreadSafe("", Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log" + "_finished.log"));
                                        }
                                    }

                                    if (!MainWindow.OnePreplaced)
                                    {
                                        // Creates a different progress file for the second preplaced (avoids negative frame progressbar)
                                        ffmpeg_progress = " -an -progress " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Progress", "split" + index.ToString("D5") + "_progress_2nd.log") + '\u0022';

                                        string encoderCMD = " -preplaced 2 " + Final_Encoder_Command;

                                        encoderCMD += " -preplacedlogfile " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022';
                                        encoderCMD += " " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".webm") + '\u0022';

                                        startInfo.Arguments = "/C ffmpeg.exe " + ffmpeg_progress + ffmpeg_input + encoderCMD;
                                        Helpers.Logging("Encoding Video: " + startInfo.Arguments);
                                        ffmpegProcess.StartInfo = startInfo;
                                        ffmpegProcess.Start();

                                        // Sets the process priority
                                        if (!Process_Priority)
                                            ffmpegProcess.PriorityClreplaced = ProcessPriorityClreplaced.BelowNormal;

                                        // Get launched Process ID
                                        int temp_pid = ffmpegProcess.Id;

                                        // Add Process ID to Array, inorder to keep track / kill the instances
                                        Global.Launched_PIDs.Add(temp_pid);

                                        ffmpegProcess.WaitForExit();

                                        // Get Exit Code
                                        exit_code = ffmpegProcess.ExitCode;

                                        if (exit_code != 0)
                                            Helpers.Logging("Chunk " + command + " Failed with Exit Code: " + exit_code.ToString());

                                        // Remove PID from Array after Exit
                                        Global.Launched_PIDs.RemoveAll(i => i == temp_pid);
                                    }

                                    if (SmallFunctions.Cancel.CancelAll == false && exit_code == 0)
                                    {
                                        // This function will write finished encodes to a log file, to be able to skip them if in resume mode
                                        Helpers.WriteToFileThreadSafe("", Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf" + "_finished.log"));
                                    }
                                }
                            }
                        }
                        finally { concurrencySemapreplaced.Release(); }
                    });
                    tasks.Add(task);
                }
                Task.WaitAll(tasks.ToArray());
            }
        }

19 View Source File : EntityBaseTest.cs
License : MIT License
Project Creator : Avanade

[Test]
        public void Property_ConcurrentUpdating()
        {
            // EnreplacedyBase etc. is not designed to be thread-sage. Not generally supported.
            var a = new TestA();
            a.TrackChanges();

            var ts = new Task[100];

            for (int i = 0; i < ts.Length; i++)
                ts[i] = CreateValueUpdateTask(a);

            for (int i = 0; i < ts.Length; i++)
                ts[i].Start();

            Task.WaitAll(ts);

            replacedert.IsNotNull(a.ChangeTracking);
            replacedert.AreEqual(4, a.ChangeTracking.Count);
            replacedert.AreEqual("Id", a.ChangeTracking[0]);
            replacedert.AreEqual("Text", a.ChangeTracking[1]);
            replacedert.AreEqual("Now", a.ChangeTracking[2]);
            replacedert.AreEqual("Time", a.ChangeTracking[3]);
        }

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 : AWSXRayRecorderTests.cs
License : Apache License 2.0
Project Creator : aws

[TestMethod]
        public async Task TestSubsegmentOutLiveParent()
        {
            var mockEmitter = new Mock<ISegmentEmitter>();

            using (var client = AWSXRayRecorderFactory.CreateAWSXRayRecorder(mockEmitter.Object))
            {
                client.BeginSegment("parent", TraceId);
                var parent = AWSXRayRecorder.Instance.TraceContext.GetEnreplacedy();

                Subsegment child = null;
                Task task = Task.Run(async () =>
                {
                    client.BeginSubsegment("child");
                    child = (Subsegment)AWSXRayRecorder.Instance.TraceContext.GetEnreplacedy();

                    await Task.Delay(1000);    // Wait for parent to end first

                    client.EndSubsegment();
                });

                await Task.Delay(50);    // Wait to ensure subsegment has started
                client.EndSegment();

                // Subsegment is not ended
                mockEmitter.Verify(x => x.Send(It.IsAny<Segment>()), Times.Never);

                Task.WaitAll(task);
                replacedert.IsNotNull(child);

                // subsegment ends
                mockEmitter.Verify(x => x.Send(It.IsAny<Segment>()), Times.Once);
            }
        }

19 View Source File : BlogTranAOP.cs
License : Apache License 2.0
Project Creator : anjoy8

public void Intercept(IInvocation invocation)
        {
            var method = invocation.MethodInvocationTarget ?? invocation.Method;
            //对当前方法的特性验证
            //如果需要验证
            if (method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(UseTranAttribute)) is UseTranAttribute)
            {
                try
                {
                    Console.WriteLine($"Begin Transaction");

                    _unitOfWork.BeginTran();

                    invocation.Proceed();


                    // 异步获取异常,先执行
                    if (IsAsyncMethod(invocation.Method))
                    {
                        var result = invocation.ReturnValue;
                        if (result is Task)
                        {
                            Task.WaitAll(result as Task);
                        }
                    }
                    _unitOfWork.CommitTran();

                }
                catch (Exception)
                {
                    Console.WriteLine($"Rollback Transaction");
                    _unitOfWork.RollbackTran();
                }
            }
            else
            {
                invocation.Proceed();//直接执行被拦截方法
            }

        }

19 View Source File : ExportContainer.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public static ExportContainer LoadFromFile(
            string file)
        {
            var data = default(ExportContainer);

            if (!File.Exists(file))
            {
                return data;
            }

            using (var sr = new StreamReader(file, new UTF8Encoding(false)))
            {
                if (sr.BaseStream.Length > 0)
                {
                    var xs = new XmlSerializer(typeof(ExportContainer));
                    data = xs.Deserialize(sr) as ExportContainer;
                }
            }

            if (data == null)
            {
                return data;
            }

            if (data.Tag != null)
            {
                data.Tag.ID = Guid.NewGuid();
            }

            var panelIDConverter = new Dictionary<Guid, Guid>();
            foreach (var panel in data.Panels)
            {
                var newID = Guid.NewGuid();
                panelIDConverter[panel.ID] = newID;
                panel.ID = newID;
            }

            var triggerIDDictionary = new Dictionary<Guid, Guid>();
            var seq = default(long);

            seq =
                SpellTable.Instance.Table.Any() ?
                SpellTable.Instance.Table.Max(x => x.ID) + 1 :
                1;
            foreach (var spell in data.Spells)
            {
                spell.ID = seq++;

                var newID = Guid.NewGuid();
                triggerIDDictionary[spell.Guid] = newID;
                spell.Guid = newID;

                if (panelIDConverter.ContainsKey(spell.PanelID))
                {
                    spell.PanelID = panelIDConverter[spell.PanelID];
                }
            }

            seq =
                TickerTable.Instance.Table.Any() ?
                TickerTable.Instance.Table.Max(x => x.ID) + 1 :
                1;
            foreach (var ticker in data.Tickers)
            {
                ticker.ID = seq++;

                var newID = Guid.NewGuid();
                triggerIDDictionary[ticker.Guid] = newID;
                ticker.Guid = newID;
            }

            // 前提条件のIDを置き換える
            Task.WaitAll(
                Task.Run(() =>
                {
                    foreach (var spell in data.Spells)
                    {
                        for (int i = 0; i < spell.TimersMustRunningForStart.Length; i++)
                        {
                            var id = spell.TimersMustRunningForStart[i];
                            if (triggerIDDictionary.ContainsKey(id))
                            {
                                spell.TimersMustRunningForStart[i] = triggerIDDictionary[id];
                            }
                        }

                        for (int i = 0; i < spell.TimersMustStoppingForStart.Length; i++)
                        {
                            var id = spell.TimersMustStoppingForStart[i];
                            if (triggerIDDictionary.ContainsKey(id))
                            {
                                spell.TimersMustStoppingForStart[i] = triggerIDDictionary[id];
                            }
                        }
                    }
                }),

                Task.Run(() =>
                {
                    foreach (var ticker in data.Tickers)
                    {
                        for (int i = 0; i < ticker.TimersMustRunningForStart.Length; i++)
                        {
                            var id = ticker.TimersMustRunningForStart[i];
                            if (triggerIDDictionary.ContainsKey(id))
                            {
                                ticker.TimersMustRunningForStart[i] = triggerIDDictionary[id];
                            }
                        }

                        for (int i = 0; i < ticker.TimersMustStoppingForStart.Length; i++)
                        {
                            var id = ticker.TimersMustStoppingForStart[i];
                            if (triggerIDDictionary.ContainsKey(id))
                            {
                                ticker.TimersMustStoppingForStart[i] = triggerIDDictionary[id];
                            }
                        }
                    }
                }));

            return data;
        }

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

public static void PrevReheatConnectionPool(ObjectPool<RedisClient> pool, int minPoolSize)
        {
            if (minPoolSize <= 0) minPoolSize = Math.Min(5, pool.Policy.PoolSize);
            if (minPoolSize > pool.Policy.PoolSize) minPoolSize = pool.Policy.PoolSize;
            var initTestOk = true;
            var initStartTime = DateTime.Now;
            var initConns = new ConcurrentBag<Object<RedisClient>>();

            try
            {
                var conn = pool.Get();
                initConns.Add(conn);
                conn.Value.Ping();
            }
            catch (Exception ex)
            {
                initTestOk = false; //预热一次失败,后面将不进行
                pool.SetUnavailable(ex);
            }
            for (var a = 1; initTestOk && a < minPoolSize; a += 10)
            {
                if (initStartTime.Subtract(DateTime.Now).TotalSeconds > 3) break; //预热耗时超过3秒,退出
                var b = Math.Min(minPoolSize - a, 10); //每10个预热
                var initTasks = new Task[b];
                for (var c = 0; c < b; c++)
                {
                    initTasks[c] = TaskEx.Run(() =>
                    {
                        try
                        {
                            var conn = pool.Get();
                            initConns.Add(conn);
                        }
                        catch
                        {
                            initTestOk = false;  //有失败,下一组退出预热
                        }
                    });
                }
                Task.WaitAll(initTasks);
            }
            while (initConns.TryTake(out var conn)) pool.Return(conn);
        }

19 View Source File : XIVApi.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void Load()
        {
            var sw = Stopwatch.StartNew();

            Task.WaitAll(
                Task.Run(() => this.LoadTerritory()),
                Task.Run(() => this.LoadArea()),
                Task.Run(() => this.LoadAction()),
                Task.Run(() => this.LoadBuff()));

            sw.Stop();
            _ = sw.Elapsed.TotalSeconds;
        }

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

[Fact]
        public void WhenParallelJobIsAllowed__TasksShouldNotWaitEachOther()
        {
            TimeSpan jobConsumeTime = TimeSpan.FromSeconds(5);

            const int jobCount = 8;
            List<Task> addTasks = new List<Task>();
            for (var i = 0; i < jobCount; i++)
            {
                LongProcessRequest longProcessRequest = new LongProcessRequest(jobConsumeTime);
                var task = _messageStorageClient.AddMessageAsync(longProcessRequest);
                addTasks.Add(task);
            }

            Task.WaitAll(addTasks.ToArray());

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            List<Task> jobProcessorTasks = new List<Task>();
            for (var i = 0; i < jobCount; i++)
            {
                var handleTask = _jobDispatcher.HandleNextJobAsync();
                jobProcessorTasks.Add(handleTask);
            }

            Task.WaitAll(jobProcessorTasks.ToArray());
            stopwatch.Stop();

            double threshold = jobConsumeTime.TotalMilliseconds * 1.5;
            _output.WriteLine($"Threshold : {threshold} ms -- Actual execution time : {stopwatch.ElapsedMilliseconds} ms");
            replacedertThat.LessThan(threshold, stopwatch.ElapsedMilliseconds);
        }

19 View Source File : TilesConverter.cs
License : MIT License
Project Creator : arcplus

internal static string CombineTilesets(string outputFolder, GisPosition gisPosition,
            params string[] objFiles)
        {
            var tasks = new Task<string>[objFiles.Length];
            for (var i = 0; i < objFiles.Length; i++)
            {
                var objFile = objFiles[i];
                var name = Path.GetFileNameWithoutExtension(objFile);
                var outputPath = Path.Combine(outputFolder, "Batched" + name);
                if (!Directory.Exists(outputPath)) Directory.CreateDirectory(outputPath);
                tasks[i] = Task.Run(() => WriteTilesetFile(objFile, outputPath, gisPosition));
            }
            Task.WaitAll(tasks);

            return CombineTilesets(outputFolder, gisPosition, tasks);
        }

19 View Source File : TilesConverter.cs
License : MIT License
Project Creator : arcplus

internal static string MergeTilesets(string outputFolder, GisPosition gisPosition, bool lod, 
            bool writeChildTilesetJson, params string[] objFiles)
        {
            var tasks = new Task<SingleTileset>[objFiles.Length];
            var outputPath = GenerateBatchedPath(outputFolder);
            if (!Directory.Exists(outputPath)) Directory.CreateDirectory(outputPath);
            for (var i = 0; i < objFiles.Length; i++)
            {
                var objFile = objFiles[i];
                var name = Path.GetFileNameWithoutExtension(objFile);
                tasks[i] = Task.Run(() => WriteTileset(objFile, outputPath, gisPosition));
            }
            Task.WaitAll(tasks);

            return MergeTilesets(outputFolder, gisPosition, lod, writeChildTilesetJson, tasks);
        }

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

[Fact]
        public void WhenParallelJobIsAllowed__TasksShouldNotWaitEachOther()
        {
            TimeSpan jobConsumeTime = TimeSpan.FromSeconds(5);

            const int jobCount = 8;
            List<Task> addTasks = new List<Task>();
            for (var i = 0; i < jobCount; i++)
            {
                LongProcessRequest longProcessRequest = new LongProcessRequest(jobConsumeTime);
                var task = _messageStorageClient.AddMessageAsync(longProcessRequest);
                addTasks.Add(task);
            }

            Task.WaitAll(addTasks.ToArray());

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            List<Task> jobProcessorTasks = new List<Task>();
            for (var i = 0; i < jobCount; i++)
            {
                var handleTask = _sut.HandleNextJobAsync();
                jobProcessorTasks.Add(handleTask);
            }

            Task.WaitAll(jobProcessorTasks.ToArray());
            stopwatch.Stop();

            double threshold = jobConsumeTime.TotalMilliseconds * 1.5;
            _output.WriteLine($"Threshold : {threshold} ms -- Actual execution time : {stopwatch.ElapsedMilliseconds} ms");
            replacedertThat.LessThan(threshold, stopwatch.ElapsedMilliseconds);
        }

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

static void Test3dTiles()
        {
            var gisPosition = new GisPosition();
            var objZipFile = @"test.objr";
            Obj23dTilesTests.WriteTilesetWithZip(objZipFile, "test", gisPosition);

            var mobjZipFile = @"testm.mobjr";
            var tasks = new Task<string>[2];
            tasks[0] = Task.Run(() =>
            Obj23dTilesTests.WriteMTilesetsWithZip(mobjZipFile, "testm", gisPosition));
            var mobjZipFile2 = @"testm2.mobjr";
            tasks[1] = Task.Run(() =>
            Obj23dTilesTests.MergeMTilesetsWithZip(mobjZipFile2, "testm2", gisPosition, true));
            Task.WaitAll(tasks);
            
        }

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

[Fact]
		public void Lock1()
		{
			var tasks = new Task[4];
			for (var a = 0; a < tasks.Length; a++)
				tasks[a] = Task.Run(() => {
					var lk = cli.Lock("testlock1", 10);
					Thread.CurrentThread.Join(1000);
					replacedert.True(lk.Unlock());
				});
			Task.WaitAll(tasks);
		}

19 View Source File : ChildProcessTest_Performance.cs
License : MIT License
Project Creator : asmichi

private static void WaitForAsyncIsTrulyAsynchronous(IChildProcess sut)
        {
            var sw = Stopwatch.StartNew();
            // Because WaitForExitAsync is truly asynchronous and does not block a thread-pool thread,
            // we can create WaitForExitAsync tasks without consuming thread-pool threads.
            // In other words, if WaitForExitAsync would consume a thread-pool thread, the works queued by Task.Run would be blocked.
            var waitTasks =
                Enumerable.Range(0, Environment.ProcessorCount * 8)
                .Select(_ => sut.WaitForExitAsync(1000))
                .ToArray();
            replacedert.True(waitTasks.All(x => !x.IsCompleted));

            var emptyTasks =
                Enumerable.Range(0, Environment.ProcessorCount * 8)
                .Select(_ => Task.Run(() => { }))
                .ToArray();
            Task.WaitAll(emptyTasks);

            replacedert.True(sw.ElapsedMilliseconds < 100);
        }

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

[Fact]
        public void TryAdd_Mulreplacedhreads_WithSameData()
        {
            var chainId = 123;
            var initTarget = 1;
            var blockInfoCache = new ChainCacheEnreplacedy(chainId, initTarget);
            var i = 0;
            var taskList = new List<Task>();
            while (i++ < 5)
            {
                var t = Task.Run(() => blockInfoCache.TryAdd(new SideChainBlockData
                {
                    Height = initTarget,
                    ChainId = chainId,
                    TransactionStatusMerkleTreeRoot = HashHelper.ComputeFrom(initTarget.ToString())
                }));
                taskList.Add(t);
            }

            Task.WaitAll(taskList.ToArray());
            replacedert.True(blockInfoCache.TargetChainHeight() == initTarget + 1);
        }

19 View Source File : DataFlowWebHookSender.cs
License : Apache License 2.0
Project Creator : aspnet

protected override void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                _disposed = true;
                if (disposing)
                {
                    if (_launchers != null)
                    {
                        try
                        {
                            // Start shutting down launchers
                            var completionTasks = new Task[_launchers.Length];
                            for (var i = 0; i < _launchers.Length; i++)
                            {
                                var launcher = _launchers[i];
                                launcher.Complete();
                                completionTasks[i] = launcher.Completion;
                            }

                            // Cancel any outstanding HTTP requests
                            if (_httpClient != null)
                            {
                                _httpClient.CancelPendingRequests();
                                _httpClient.Dispose();
                            }

                            // Wait for launchers to complete
                            Task.WaitAll(completionTasks);
                        }
                        catch (Exception ex)
                        {
                            ex = ex.GetBaseException();
                            var message = string.Format(CultureInfo.CurrentCulture, CustomResources.Manager_CompletionFailure, ex.Message);
                            Logger.Error(message, ex);
                        }
                    }
                }
                base.Dispose(disposing);
            }
        }

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 : LoadTestService.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

public void ExecuteForTime(int numberOfProcesses, int pauseBetweenStartSeconds, int secondsToBeExecuted, Action testBody)
        {
            if (numberOfProcesses <= 0)
            {
                throw new ArgumentException($"Number of processes should be a positive number.");
            }

            if (pauseBetweenStartSeconds < 0)
            {
                throw new ArgumentException($"Pause between start of processes should be a positive number.");
            }

            if (secondsToBeExecuted < 0)
            {
                throw new ArgumentException($"Seconds to be executed should be a positive number.");
            }

            var stopWatch = new Stopwatch();
            stopWatch.Start();
            do
            {
                var loadTasks = CreateTestTasks(numberOfProcesses, pauseBetweenStartSeconds, testBody);
                Task.WaitAll(loadTasks.ToArray());
            }
            while (stopWatch.Elapsed.TotalSeconds < secondsToBeExecuted);

            stopWatch.Stop();
        }

19 View Source File : VWAP.cs
License : Apache License 2.0
Project Creator : AlexWan

private void ProcessAll(List<Candle> candles)
        {
            if (candles == null)
            {
                return;
            }

            if (_decimals == 0 && candles.Count != 0)
            {
                var price = candles[0].Open;
                _decimals = BitConverter.GetBytes(decimal.GetBits(price)[3])[2];
            }

            ResetValues();

            _calculationInProgress = true;
            var tasks = new Task[3];
            try
            {
                if (UseDate)
                {
                    var task = Task.Run(delegate { ProcessDate(candles); });
                    tasks[0] = task;
                }
                else
                {
                    var task = Task.Run(() => Task.Delay(1));
                    tasks[0] = task;
                }

                if (UseDay)
                {
                    var task = Task.Run(delegate { ProcessOneDay(candles); });
                    tasks[1] = task;
                }
                else
                {
                    var task = Task.Run(() => Task.Delay(1));
                    tasks[1] = task;
                }

                if (UseWeekly)
                {
                    var task = Task.Run(delegate { ProcessWeek(candles); });
                    tasks[2] = task;
                }
                else
                {
                    var task = Task.Run(() => Task.Delay(1));
                    tasks[2] = task;
                }

                Task.WaitAll(tasks);
            }
            finally
            {
                _calculationInProgress = false;
            }
        }

19 View Source File : ReferenceDataMultiTenantCacheTest.cs
License : MIT License
Project Creator : Avanade

[Test]
        public void Concurrency()
        {
            var sp = UnitTest.Caching.Policy.CachePolicyManagerTest.TestSetUp();

            int i = 0;
            var rdc = new ReferenceDataMulreplacedenantCache<TestRdCollection, TestRd>(() => { i++; return GetData(); });

            ExecutionContext.Reset();

            // Set an execution context.
            var tasks = new Task[10];
            tasks[0] = Task.Run(() => Timer(0, GetGuid(08), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(08), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[1] = Task.Run(() => Timer(1, GetGuid(09), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(09), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[2] = Task.Run(() => Timer(2, GetGuid(1), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(1), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[3] = Task.Run(() => Timer(3, GetGuid(2), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(2), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[4] = Task.Run(() => Timer(4, GetGuid(08), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(08), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[5] = Task.Run(() => Timer(5, GetGuid(09), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(09), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[6] = Task.Run(() => Timer(6, GetGuid(1), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(1), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[7] = Task.Run(() => Timer(7, GetGuid(2), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(2), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[8] = Task.Run(() => Timer(8, GetGuid(08), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(08), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[9] = Task.Run(() => Timer(9, GetGuid(09), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(09), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));

            Task.WaitAll(tasks);

            TestContext.WriteLine("ROUND TWO");

            tasks = new Task[10];
            tasks[0] = Task.Run(() => Timer(0, GetGuid(08), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(08), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[1] = Task.Run(() => Timer(1, GetGuid(09), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(09), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[2] = Task.Run(() => Timer(2, GetGuid(1), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(1), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[3] = Task.Run(() => Timer(3, GetGuid(2), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(2), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[4] = Task.Run(() => Timer(4, GetGuid(08), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(08), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[5] = Task.Run(() => Timer(5, GetGuid(09), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(09), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[6] = Task.Run(() => Timer(6, GetGuid(1), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(1), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[7] = Task.Run(() => Timer(7, GetGuid(2), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(2), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[8] = Task.Run(() => Timer(8, GetGuid(08), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(08), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));
            tasks[9] = Task.Run(() => Timer(9, GetGuid(09), () => { ExecutionContext.SetCurrent(new ExecutionContext { TenantId = GetGuid(09), ServiceProvider = sp }); replacedert.IsTrue(rdc.GetCollection().ActiveList.Count > 0); }));

            Task.WaitAll(tasks);
        }

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 : TwoKeyValueCacheTest.cs
License : MIT License
Project Creator : Avanade

[Test]
        public void Concurrency()
        {
            Policy.CachePolicyManagerTest.TestSetUp();

            // No way to effectively validate; console output needs to be reviewed.

            int key1Count = 0;
            int key2Count = 0;
            int dataValue1 = 100;
            int dataValue2 = 200;

            var random = new System.Random();

            var mtc = new TwoKeyValueCache<int, string, string>(
                (key1) => { System.Console.WriteLine($"get1 >> {key1Count++}"); Thread.Sleep(random.Next(0, 10)); return (key1 == 99) ? (false, null, null) : (true, key1.ToString(), $"x{dataValue1++}x"); },
                (key2) => { System.Console.WriteLine($"get2 >> {key2Count++}"); Thread.Sleep(random.Next(0, 10)); return (true, int.Parse(key2), $"y{dataValue2++}y"); },
                "TwoKeyValueCacheTest2");

            var tasks = new Task[9];

            for (int i = 0; i < 10; i++)
            {
                if (i % 2 == 0)
                { 
                    tasks[0] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); var r = mtc.GetByKey1(1); System.Console.WriteLine($"0 >> {r}"); });
                    tasks[1] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); var r = mtc.GetByKey2("1"); System.Console.WriteLine($"1 >> {r}"); });
                    tasks[2] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); var r = mtc.GetByKey1(1); System.Console.WriteLine($"2 >> {r}"); });
                    tasks[3] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); var r = mtc.GetByKey2("1"); System.Console.WriteLine($"3 >> {r}"); });
                    tasks[4] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); System.Console.WriteLine("4 >> removed"); mtc.Remove2("1"); });
                    tasks[5] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); var r = mtc.GetByKey1(1); System.Console.WriteLine($"5 >> {r}"); });
                    tasks[6] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); var r = mtc.GetByKey2("1"); System.Console.WriteLine($"6 >> {r}"); });
                    tasks[7] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); var r = mtc.GetByKey1(1); System.Console.WriteLine($"7 >> {r}"); });
                    tasks[8] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); var r = mtc.GetByKey2("1"); System.Console.WriteLine($"8 >> {r}"); });

                    Task.WaitAll(tasks);

                    System.Console.WriteLine($"one> key1: {key1Count}; key2: {key2Count}");
                }
                else
                {
                    tasks[0] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); var r = mtc.GetByKey2("1"); System.Console.WriteLine($"0 >> {r}"); });
                    tasks[1] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); var r = mtc.GetByKey1(1); System.Console.WriteLine($"1 >> {r}"); });
                    tasks[2] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); var r = mtc.GetByKey2("1"); System.Console.WriteLine($"2 >> {r}"); });
                    tasks[3] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); var r = mtc.GetByKey1(1); System.Console.WriteLine($"3 >> {r}"); });
                    tasks[4] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); System.Console.WriteLine("4 >> removed"); mtc.Remove1(1); });
                    tasks[5] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); var r = mtc.GetByKey2("1"); System.Console.WriteLine($"5 >> {r}"); });
                    tasks[6] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); var r = mtc.GetByKey1(1); System.Console.WriteLine($"6 >> {r}"); });
                    tasks[7] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); var r = mtc.GetByKey2("1"); System.Console.WriteLine($"7 >> {r}"); });
                    tasks[8] = Task.Run(() => { Thread.Sleep(random.Next(0, 10)); var r = mtc.GetByKey2("1"); System.Console.WriteLine($"8 >> {r}"); });

                    Task.WaitAll(tasks);

                    System.Console.WriteLine($"two> key1: {key1Count}; key2: {key2Count}");
                }
            }
        }

19 View Source File : EncodeVideoPipe.cs
License : MIT License
Project Creator : Alkl58

public static void Encode()
        {
            // Main Encoding Function
            // Creates a new Thread Pool
            using (SemapreplacedSlim concurrencySemapreplaced = new SemapreplacedSlim(EncodeVideo.Worker_Count))
            {
                // Creates a tasks list
                List<Task> tasks = new List<Task>();
                // Iterates over all args in VideoChunks list
                foreach (var command in Global.Video_Chunks)
                {
                    concurrencySemapreplaced.Wait();
                    var task = Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            if (!SmallFunctions.Cancel.CancelAll)
                            {
                                // We need the index of the command in the array
                                var index = Array.FindIndex(Global.Video_Chunks, row => row.Contains(command));
                                // Logic for resume mode - skips already encoded files
                                if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf" + "_finished.log")) == false)
                                {
                                    // One Preplaced Encoding
                                    Process ffmpegProcess = new Process();
                                    ProcessStartInfo startInfo = new ProcessStartInfo
                                    {
                                        UseShellExecute = true,
                                        FileName = "cmd.exe",
                                        WorkingDirectory = Global.FFmpeg_Path
                                    };

                                    if (!EncodeVideo.Show_Terminal)
                                    {
                                        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                                    }

                                    string InputVideo = "";

                                    if (Splitting.split_type >= 1)
                                    {
                                        // FFmpeg Scene Detect or PySceneDetect
                                        InputVideo = " -i " + '\u0022' + Global.Video_Path + '\u0022' + " " + command;
                                    }
                                    else if (Splitting.split_type == 0)
                                    {
                                        // Chunk based splitting
                                        InputVideo = " -i " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", command) + '\u0022';
                                    }

                                    // Saves encoder progress to log file
                                    string ffmpeg_progress = " -progress " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Progress", "split" + index.ToString("D5") + "_progress.log") + '\u0022';

                                    // FFmpeg Pipe
                                    string ffmpeg_input = InputVideo + " " + MainWindow.FilterCommand + EncodeVideo.Pixel_Format + " -color_range 0 " + MainWindow.VSYNC + " -f yuv4mpegpipe - | ";

                                    // Process Exit Code
                                    int exit_code = 0;

                                    // Logic to skip first preplaced encoding if "_finished" log file exists
                                    if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log" + "_finished.log")) == false)
                                    {
                                        string encoderCMD = "";

                                        if (MainWindow.OnePreplaced)
                                        {
                                            // One Preplaced Encoding

                                            if (MainWindow.EncodeMethod == 5)
                                            {
                                                // aomenc
                                                encoderCMD = '\u0022' + Path.Combine(Global.Aomenc_Path, "aomenc.exe") + '\u0022' + " - --preplacedes=1 " + EncodeVideo.Final_Encoder_Command + " --output=";
                                            }
                                            else if (MainWindow.EncodeMethod == 6)
                                            {
                                                // rav1e
                                                encoderCMD = '\u0022' + Path.Combine(Global.Rav1e__Path, "rav1e.exe") + '\u0022' + " - " + EncodeVideo.Final_Encoder_Command + " --output ";
                                            }
                                            else if (MainWindow.EncodeMethod == 7)
                                            {
                                                // svt-av1
                                                ffmpeg_input = InputVideo + " " + MainWindow.FilterCommand + EncodeVideo.Pixel_Format + " -color_range 0 -nostdin " + MainWindow.VSYNC + " -f yuv4mpegpipe - | ";
                                                encoderCMD = '\u0022' + Path.Combine(Global.SvtAv1_Path, "SvtAv1EncApp.exe") + '\u0022' + " -i stdin " + EncodeVideo.Final_Encoder_Command + " --preplacedes 1 -b ";
                                            }

                                            encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf") + '\u0022';
                                        }
                                        else
                                        {
                                            // Two Preplaced Encoding - First Preplaced

                                            if (MainWindow.EncodeMethod == 5)
                                            {
                                                // aomenc
                                                encoderCMD = '\u0022' + Path.Combine(Global.Aomenc_Path, "aomenc.exe") + '\u0022' + " - --preplacedes=2 --preplaced=1 " + EncodeVideo.Final_Encoder_Command + " --fpf=";
                                                encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022' + " --output=NUL";
                                            }
                                            else if (MainWindow.EncodeMethod == 7)
                                            {
                                                // svt-av1
                                                ffmpeg_input = InputVideo + " " + MainWindow.FilterCommand + EncodeVideo.Pixel_Format + " -color_range 0 -nostdin " + MainWindow.VSYNC + " -f yuv4mpegpipe - | ";
                                                encoderCMD = '\u0022' + Path.Combine(Global.SvtAv1_Path, "SvtAv1EncApp.exe") + '\u0022' + " -i stdin " + EncodeVideo.Final_Encoder_Command + " --irefresh-type 2 --preplaced 1 -b NUL --stats ";
                                                encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022';
                                            }
                                        }

                                        startInfo.Arguments = "/C ffmpeg.exe " + ffmpeg_progress + ffmpeg_input + encoderCMD;

                                        Helpers.Logging("Encoding Video: " + startInfo.Arguments);
                                        ffmpegProcess.StartInfo = startInfo;
                                        ffmpegProcess.Start();

                                        // Sets the process priority
                                        if (!EncodeVideo.Process_Priority)
                                            ffmpegProcess.PriorityClreplaced = ProcessPriorityClreplaced.BelowNormal;

                                        // Get launched Process ID
                                        int temp_pid = ffmpegProcess.Id;

                                        // Add Process ID to Array, inorder to keep track / kill the instances
                                        Global.Launched_PIDs.Add(temp_pid);

                                        ffmpegProcess.WaitForExit();

                                        // Get Exit Code
                                        exit_code = ffmpegProcess.ExitCode;

                                        if (exit_code != 0)
                                            Helpers.Logging("Chunk " + command + " Failed with Exit Code: " + exit_code.ToString());

                                        // Remove PID from Array after Exit
                                        Global.Launched_PIDs.RemoveAll(i => i == temp_pid);

                                        if (MainWindow.OnePreplaced == false && SmallFunctions.Cancel.CancelAll == false && exit_code == 0)
                                        {
                                            // Writes log file if first preplaced is finished, to be able to skip them later if in resume mode
                                            Helpers.WriteToFileThreadSafe("", Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log" + "_finished.log"));
                                        }
                                    }

                                    if (!MainWindow.OnePreplaced)
                                    {
                                        // Creates a different progress file for the second preplaced (avoids negative frame progressbar)
                                        ffmpeg_progress = " -progress " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Progress", "split" + index.ToString("D5") + "_progress_2nd.log") + '\u0022';

                                        string encoderCMD = "";

                                        if (MainWindow.EncodeMethod == 5)
                                        {
                                            // aomenc
                                            encoderCMD = '\u0022' + Path.Combine(Global.Aomenc_Path, "aomenc.exe") + '\u0022' + " - --preplacedes=2 --preplaced=2 " + EncodeVideo.Final_Encoder_Command + " --fpf=";
                                            encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022' + " --output=";
                                        }
                                        else if (MainWindow.EncodeMethod == 7)
                                        {
                                            // svt-av1
                                            ffmpeg_input = InputVideo + " " + MainWindow.FilterCommand + EncodeVideo.Pixel_Format + " -color_range 0 -nostdin " + MainWindow.VSYNC + " -f yuv4mpegpipe - | ";
                                            encoderCMD = '\u0022' + Path.Combine(Global.SvtAv1_Path, "SvtAv1EncApp.exe") + '\u0022' + " -i stdin " + EncodeVideo.Final_Encoder_Command + " --irefresh-type 2 --preplaced 2 --stats ";
                                            encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022' + " -b ";
                                        }

                                        encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf") + '\u0022';

                                        startInfo.Arguments = "/C ffmpeg.exe " + ffmpeg_progress + ffmpeg_input + encoderCMD;
                                        Helpers.Logging("Encoding Video: " + startInfo.Arguments);
                                        ffmpegProcess.StartInfo = startInfo;
                                        ffmpegProcess.Start();

                                        // Sets the process priority
                                        if (!EncodeVideo.Process_Priority)
                                            ffmpegProcess.PriorityClreplaced = ProcessPriorityClreplaced.BelowNormal;

                                        // Get launched Process ID
                                        int temp_pid = ffmpegProcess.Id;

                                        // Add Process ID to Array, inorder to keep track / kill the instances
                                        Global.Launched_PIDs.Add(temp_pid);

                                        ffmpegProcess.WaitForExit();

                                        // Get Exit Code
                                        exit_code = ffmpegProcess.ExitCode;

                                        if (exit_code != 0)
                                            Helpers.Logging("Chunk " + command + " Failed with Exit Code: " + exit_code.ToString());

                                        // Remove PID from Array after Exit
                                        Global.Launched_PIDs.RemoveAll(i => i == temp_pid);
                                    }

                                    if (SmallFunctions.Cancel.CancelAll == false && exit_code == 0)
                                    {
                                        // This function will write finished encodes to a log file, to be able to skip them if in resume mode
                                        Helpers.WriteToFileThreadSafe("", Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf" + "_finished.log"));
                                    }
                                }
                            }
                        }
                        finally { concurrencySemapreplaced.Release(); }
                    });
                    tasks.Add(task);
                }
                Task.WaitAll(tasks.ToArray());
            }
        }

19 View Source File : ConfigurtaionBuilderIntegrationTestFixture.cs
License : Apache License 2.0
Project Creator : aws

private void seedTestData()
        {
            bool success = false;
            using (var client = AWSOptions.CreateServiceClient<IAmazonSimpleSystemsManagement>())
            {
                var tasks = new List<Task>();
                foreach (var kv in TestData)
                {
                    Console.WriteLine($"Adding parameter: ({ParameterPrefix + kv.Key}, {kv.Value})");
                    tasks.Add(client.PutParameterAsync(new PutParameterRequest
                    {
                        Name = ParameterPrefix + kv.Key,
                        Value = kv.Value,
                        Type = ParameterType.String
                    }));
                };
                Task.WaitAll(tasks.ToArray());

                // due to eventual consistency, wait for 5 sec increments for 3 times to verify
                // test data is correctly set before executing tests.
                const int tries = 3;
                for (int i = 0; i < tries; i++)
                {
                    int count = 0;
                    GetParametersByPathResponse response;
                    do
                    {
                        response = client.GetParametersByPathAsync(new GetParametersByPathRequest
                        {
                            Path = ParameterPrefix
                        }).Result;

                        count += response.Parameters.Count;
                    } while (!string.IsNullOrEmpty(response.NextToken));

                    success = (count == TestData.Count);

                    if (success)
                    {
                        Console.WriteLine("Verified that test data is available.");
                        break;
                    }
                    else
                    {
                        Console.WriteLine($"Waiting on test data to be available. Waiting {count + 1}/{tries}");
                        Thread.Sleep(5 * 1000);
                    }
                }
            }

            if (!success) throw new Exception("Failed to seed integration test data");
        }

19 View Source File : OneCmdShell.cs
License : MIT License
Project Creator : 1y0n

public void Http_server_task()
        {
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://" + textBox1.Text + ":" + textBox2.Text + "/");
            listener.Start();
            Global_Var.Http_server_status = true;
            label4.Text = "服务已开启在 " + textBox2.Text + " 端口";
            label4.ForeColor = Color.Green;
            Global_Var.HTTP_Port = textBox2.Text;
            Task task = Task.Factory.StartNew(() => {
                while (listener.IsListening && !stop)
                {
                    HttpListenerContext context = listener.GetContext();
                    HttpListenerRequest request = context.Request;
                    HttpListenerResponse response = context.Response;
                    using (StreamWriter writer = new StreamWriter(response.OutputStream))
                    {
                        writer.WriteLine(Global_Var.XSL_code);
                    }
                }
            });
            Task.WaitAll();
        }

19 View Source File : AWSXRayRecorderTests.cs
License : Apache License 2.0
Project Creator : aws

[TestMethod]
        public void TaskAsyncCreateThousandSubsegments()
        {
            _recorder.BeginSegment("parent", TraceId);
            Segment parent = (Segment)AWSXRayRecorder.Instance.TraceContext.GetEnreplacedy();

            Action action = () =>
            {
                _recorder.BeginSubsegment("child");
                _recorder.EndSubsegment();
            };

            var tasks = new Task[1000];
            for (int i = 0; i < 1000; i++)
            {
                tasks[i] = Task.Run(action);
            }

            Task.WaitAll(tasks);

            _recorder.EndSegment();

            replacedert.IsTrue(parent.Subsegments.Count < 100);
            replacedert.AreEqual(0, parent.Reference);
            replacedert.AreEqual(parent.Size, parent.Subsegments.Count);
        }

19 View Source File : Scheduler.cs
License : MIT License
Project Creator : anet-team

public async static Task StopAll()
        {
            if (_issStopping) return;
            _issStopping = true;

            _enabled = false;
            _timer.Change(-1, -1);

            await Task.Run(() =>
            {
                var tasks = new Task[0];
                do
                {
                    lock (_running)
                    {
                        tasks = _running.Select(t => t.Item2).ToArray();
                    }
                    Task.WaitAll(tasks);
                } while (tasks.Any());
                _issStopping = false;
            });
        }

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

[ReleaseModeTheory]
        [InlineData(2000, 20000)]
        [InlineData(1000, 10000)]
        [InlineData(100, 1000)]
        public void When_AddMessageCalled__ResponseTimeShouldNotExceed(int times, int expectedMilliseconds)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            List<Task> tasks = new List<Task>();
            for (int 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.Stop();

            string message = $"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 : CodeFirstProviderAbstract.cs
License : MIT License
Project Creator : 17MKH

public virtual void InitData(IRepositoryManager repositoryManager)
    {
        if (!Options.InitData)
            return;


        if (Options.InitDataFilePath.IsNull() || !File.Exists(Options.InitDataFilePath))
        {
            _logger.LogDebug("初始化数据文件不存在");
            return;
        }

        _logger.LogDebug("开始初始化数据");

        var jsonHelper = new JsonHelper();

        using var jsonReader = new StreamReader(Options.InitDataFilePath, Encoding.UTF8);
        var str = jsonReader.ReadToEnd();

        using var doc = JsonDoreplacedent.Parse(str);
        var properties = doc.RootElement.EnumerateObject();
        if (properties.Any())
        {
            foreach (var property in properties)
            {
                var enreplacedyDescriptor = Context.EnreplacedyDescriptors.FirstOrDefault(m => m.Name.EqualsIgnoreCase(property.Name));
                if (enreplacedyDescriptor != null)
                {
                    var list = (IList)jsonHelper.Deserialize(property.Value.ToString(),
                        typeof(List<>).MakeGenericType(enreplacedyDescriptor.EnreplacedyType));

                    var repositoryDescriptor = Context.RepositoryDescriptors.FirstOrDefault(m => m.EnreplacedyType == enreplacedyDescriptor.EnreplacedyType);

                    var repository = (IRepository)Service.BuildServiceProvider()
                        .GetService(repositoryDescriptor!.InterfaceType);

                    var tasks = new List<Task>();
                    foreach (var item in list)
                    {
                        tasks.Add(repository.Add(item));
                    }

                    Task.WaitAll(tasks.ToArray());
                }
            }
        }
    }

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

[Fact]
		public void Lock1() {
			var tasks = new Task[4];
			for (var a = 0; a < tasks.Length; a++)
				tasks[a] = Task.Run(() => {
					var lk = rds.Lock("testlock1", 10);
					Thread.CurrentThread.Join(1000);
					replacedert.True(lk.Unlock());
				});
			Task.WaitAll(tasks);
		}

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

public static void PrevReheatConnectionPool(ObjectPool<RedisClient> pool, int minPoolSize)
        {
            if (minPoolSize <= 0) minPoolSize = Math.Min(5, pool.Policy.PoolSize);
            if (minPoolSize > pool.Policy.PoolSize) minPoolSize = pool.Policy.PoolSize;
            var initTestOk = true;
            var initStartTime = DateTime.Now;
            var initConns = new ConcurrentBag<Object<RedisClient>>();

            try
            {
                var conn = pool.Get();
                initConns.Add(conn);
                pool.Policy.OnCheckAvailable(conn);
            }
            catch (Exception ex)
            {
                initTestOk = false; //预热一次失败,后面将不进行
                pool.SetUnavailable(ex);
            }
            for (var a = 1; initTestOk && a < minPoolSize; a += 10)
            {
                if (initStartTime.Subtract(DateTime.Now).TotalSeconds > 3) break; //预热耗时超过3秒,退出
                var b = Math.Min(minPoolSize - a, 10); //每10个预热
                var initTasks = new Task[b];
                for (var c = 0; c < b; c++)
                {
                    initTasks[c] = TaskEx.Run(() =>
                    {
                        try
                        {
                            var conn = pool.Get();
                            initConns.Add(conn);
                            pool.Policy.OnCheckAvailable(conn);
                        }
                        catch
                        {
                            initTestOk = false;  //有失败,下一组退出预热
                        }
                    });
                }
                Task.WaitAll(initTasks);
            }
            while (initConns.TryTake(out var conn)) pool.Return(conn);
        }

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 : TilesConverter.cs
License : MIT License
Project Creator : arcplus

internal static string CombineTilesets(string objFolder, string outputFolder, GisPosition gisPosition,
            params ObjModel[] objModels)
        {
            var tasks = new Task<string>[objModels.Length];
            for (var i = 0; i < objModels.Length; i++)
            {
                var objFile = objModels[i];
                var name = objFile.Name;
                var outputPath = Path.Combine(outputFolder, "Batched" + name);
                if (!Directory.Exists(outputPath)) Directory.CreateDirectory(outputPath);
                tasks[i] = Task.Run(() => WriteTilesetFile(objFile, objFolder, outputPath, gisPosition));
            }
            Task.WaitAll(tasks);

            return CombineTilesets(outputFolder, gisPosition, tasks);
        }

See More Examples