Exemple #1
0
        public static void Test()
        {
            //metody Paraller.* zoptymalizowane są pod kątem obliczeń, a nie operacji wejścia wyjścia, ale np nadaje się na pobranie dwóch stron internetowcyh
            //Parallel.Invoke(
            //    ()=>new WebClient().DownloadFile("http://www.linqpad.net","lp.html"),
            //    ()=>new WebClient().DownloadFile("http://www.jaoo.dk","jaoo.html")
            //    );
            //przyjmuje tablice delegatów action do wykonania
            //dziąła efektywnie nawet przy milinione delegatów, lepiej niż taski bo nie tworzy osobnego zadania dla kazdego delegatu

            //var kePairs = new string[6];
            //Parallel.For(0, kePairs.Length, i => kePairs[i] = RSA.Create().ToXmlString(true));
            ////lub w tym przypadku tez moze byc za pomcoą plinq
            //string[] keyPairs = ParallelEnumerable.Range(0, 6).Select(i => RSA.Create().ToXmlString(true)).ToArray();

            ////gdy mamy pętle wewnętrzne i zewnętrzne lepiej zrównoleglić tylko zewnętrzne

            //Parallel.ForEach("Hello World", (c, state, i) =>
            //{
            //    Console.WriteLine(c.ToString() + i);
            //});

            //Parallel.ForEach("Hello World", (c, state) =>
            //{
            //    if (c==' ')
            //    {
            //        state.Break();
            //    }
            //    else
            //    {
            //        Console.Write(c);
            //    }
            //});
            //można tęż state.Stop gdy dostalismy to czego chcielismy lubgdyby coś nie wyszło i nie interesują nas wyniki
            //foreach i for zwracaja obiekt ParallelLoopResult


            //suma 10 000 000 pierwiastków równolegle
            object locker     = new object();
            double grandTotal = 0;

            Parallel.For(1, 10000000,
                         () => 0.0,                                           //inicjalizacja wartosci lokalnej
                         (i, state, localTotal) => localTotal + Math.Sqrt(i), //zwwraca nową sumę lokalną
                         localTotal =>
            {
                lock (locker)
                {
                    grandTotal += localTotal;    //dodwanaie wartosci lokalnej do wartosci głównej
                }
            }
                         );
            Console.WriteLine(grandTotal);
            //można też za pomocą plinq
            var wynik = ParallelEnumerable.Range(1, 10000000 - 1).Sum(i => Math.Sqrt(i));//zwróc uwage na -1

            Console.WriteLine(wynik);

            double grand2 = 0;

            for (int i = 1; i < 10000000; i++)
            {
                grand2 += Math.Sqrt(i);
            }
            Console.WriteLine($"Sekwencyjnie: {grand2}");
        }
        public static void Show()
        {
            // OutputSide Optimization 输出端优化
            {
                // ForAll 不考虑输出元素顺序,并在每个输出元素上执行委托
                "abcdef".AsParallel().Select(c => char.ToUpper(c)).ForAll(Console.Write);
            }
            // InputSide Optimization 输入端优化
            // 输入端三种划分策略: 块划分、范围划分、散列划分
            {
                // 块划分:输入序列五索引无序集合
                // 让各个线程保持同等忙碌的状态,但从共享的输入序列中获取元素需要进行同步,同步会带来竞争和开销
                {
                    int[] numbers = { 3, 4, 5, 6, 7, 8, 9 };

                    var parallelQuery =
                        Partitioner.Create(numbers, true).AsParallel()
                        .Where(n => n % 2 == 0);
                    parallelQuery.Dump();
                }
                // 范围划分:输入序列有索引,输入序列长,元素执行时间大致相等,如IList<T>
                // 预先给每一个工作线程分配同等数量的元素,避免输入序列上竞争
                {
                    ParallelEnumerable.Range(1, 100000000).Sum(i => Math.Sqrt(i));
                }
            }
            // Aggregations Optimization 聚合优化
            // 为输入序列生成多个种子,从而可以从多个分块序列中聚合
            {
                // 简单使用 Sum求和
                {
                    int[] numbers = { 3, 4, 5, 6, 7, 8, 9 };
                    int   sum     = numbers.Aggregate(0, (total, n) => total + n);
                }
                // 种子工厂
                {
                    {
                        int[] numbers = { 3, 4, 5, 6, 7, 8, 9 };
                        numbers.AsParallel().Aggregate(
                            () => 0,                                           // SeedFactory 返回一个新的本地累加器 localTotal = 0
                            (localTotal, n) => localTotal + n,                 // UpdateAccumulatorFunc 将聚合到本地累加器
                            (mainTotal, localTotal) => mainTotal + localTotal, // CombineAccumulatorFunc 将本地累加器与主累加器结合
                            finalResult => finalResult);                       // ResultSelector 在最终的结果上应用任意的转换
                    }
                    // 统计字母出现频率
                    {
                        // Foreach 版本
                        string text = "Let’s suppose this is a really long string";
                        var    letterFrequencies = new int[26];
                        foreach (char c in text)
                        {
                            int index = char.ToUpper(c) - 'A';
                            if (index >= 0 && index <= 26)
                            {
                                letterFrequencies[index]++;
                            }
                        }
                        ;
                        letterFrequencies.Dump();

                        // Aggregate 顺序版本
                        int[] result = text.Aggregate(
                            new int[26],
                            (letterFreqs, c) =>
                        {
                            int index = char.ToUpper(c) - 'A';
                            if (index >= 0 && index <= 26)
                            {
                                letterFreqs[index]++;
                            }
                            return(letterFreqs);
                        }
                            );
                        result.Dump();

                        // Aggregate 并行版本
                        int[] resultAsync = text.AsParallel().
                                            Aggregate(
                            () => new int[26],
                            (localFreqs, c) =>
                        {
                            int index = char.ToUpper(c) - 'A';
                            if (index >= 0 && index <= 26)
                            {
                                localFreqs[index]++;
                            }
                            return(localFreqs);
                        },
                            (mainFreqs, localFreqs) => mainFreqs.Zip(localFreqs, (f1, f2) => f1 + f2).ToArray(),
                            finalResult => finalResult
                            );
                    }
                }
            }
        }
Exemple #3
0
        public static void Except_ArgumentNullException()
        {
            Assert.Throws <ArgumentNullException>("first", () => ((ParallelQuery <int>)null).Except(ParallelEnumerable.Range(0, 1)));
            Assert.Throws <ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Except(null));

            Assert.Throws <ArgumentNullException>("first", () => ((ParallelQuery <int>)null).Except(ParallelEnumerable.Range(0, 1), EqualityComparer <int> .Default));
            Assert.Throws <ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Except(null, EqualityComparer <int> .Default));
        }
Exemple #4
0
 public static void Sum_Long_SomeNull(int count)
 {
     Assert.Equal(Functions.SumRange(0, count / 2), ParallelEnumerable.Range(0, count).Select(x => x < count / 2 ? (long?)x : null).Sum());
     Assert.Equal(-Functions.SumRange(0, count / 2), ParallelEnumerable.Range(0, count).Sum(x => x < count / 2 ? -(long?)x : null));
 }
Exemple #5
0
 public static void Any_ArgumentNullException()
 {
     Assert.Throws <ArgumentNullException>(() => ((ParallelQuery <bool>)null).Any(x => x));
     Assert.Throws <ArgumentNullException>(() => ParallelEnumerable.Empty <bool>().Any(null));
 }
Exemple #6
0
        internal override bool MoveNext(ref TOutput currentElement, ref TLeftKey currentKey)
        {
            Mutables <TLeftInput, TLeftKey, TRightInput, THashKey, TOutput> mutables = this.m_mutables;

            if (mutables == null)
            {
                mutables = this.m_mutables = new Mutables <TLeftInput, TLeftKey, TRightInput, THashKey, TOutput>();
                mutables.m_rightHashLookup = new HashLookup <THashKey, Pair <TRightInput, ListChunk <TRightInput> > >(this.m_keyComparer);
                Pair <TRightInput, THashKey> pair = new Pair <TRightInput, THashKey>();
                int num  = 0;
                int num2 = 0;
                while (this.m_rightSource.MoveNext(ref pair, ref num))
                {
                    if ((num2++ & 0x3f) == 0)
                    {
                        CancellationState.ThrowIfCanceled(this.m_cancellationToken);
                    }
                    TRightInput first  = pair.First;
                    THashKey    second = pair.Second;
                    if (second != null)
                    {
                        Pair <TRightInput, ListChunk <TRightInput> > pair2 = new Pair <TRightInput, ListChunk <TRightInput> >();
                        if (!mutables.m_rightHashLookup.TryGetValue(second, ref pair2))
                        {
                            pair2 = new Pair <TRightInput, ListChunk <TRightInput> >(first, null);
                            if (this.m_groupResultSelector != null)
                            {
                                pair2.Second = new ListChunk <TRightInput>(2);
                                pair2.Second.Add(first);
                            }
                            mutables.m_rightHashLookup.Add(second, pair2);
                        }
                        else
                        {
                            if (pair2.Second == null)
                            {
                                pair2.Second = new ListChunk <TRightInput>(2);
                                mutables.m_rightHashLookup[second] = pair2;
                            }
                            pair2.Second.Add(first);
                        }
                    }
                }
            }
            ListChunk <TRightInput> currentRightMatches = mutables.m_currentRightMatches;

            if ((currentRightMatches != null) && (mutables.m_currentRightMatchesIndex == currentRightMatches.Count))
            {
                currentRightMatches = mutables.m_currentRightMatches = currentRightMatches.Next;
                mutables.m_currentRightMatchesIndex = 0;
            }
            if (mutables.m_currentRightMatches == null)
            {
                Pair <TLeftInput, THashKey> pair3 = new Pair <TLeftInput, THashKey>();
                TLeftKey local3 = default(TLeftKey);
                while (this.m_leftSource.MoveNext(ref pair3, ref local3))
                {
                    if ((mutables.m_outputLoopCount++ & 0x3f) == 0)
                    {
                        CancellationState.ThrowIfCanceled(this.m_cancellationToken);
                    }
                    Pair <TRightInput, ListChunk <TRightInput> > pair4 = new Pair <TRightInput, ListChunk <TRightInput> >();
                    TLeftInput local4 = pair3.First;
                    THashKey   key    = pair3.Second;
                    if (((key != null) && mutables.m_rightHashLookup.TryGetValue(key, ref pair4)) && (this.m_singleResultSelector != null))
                    {
                        mutables.m_currentRightMatches      = pair4.Second;
                        mutables.m_currentRightMatchesIndex = 0;
                        currentElement = this.m_singleResultSelector(local4, pair4.First);
                        currentKey     = local3;
                        if (pair4.Second != null)
                        {
                            mutables.m_currentLeft    = local4;
                            mutables.m_currentLeftKey = local3;
                        }
                        return(true);
                    }
                    if (this.m_groupResultSelector != null)
                    {
                        IEnumerable <TRightInput> enumerable = pair4.Second;
                        if (enumerable == null)
                        {
                            enumerable = (IEnumerable <TRightInput>)ParallelEnumerable.Empty <TRightInput>();
                        }
                        currentElement = this.m_groupResultSelector(local4, enumerable);
                        currentKey     = local3;
                        return(true);
                    }
                }
                return(false);
            }
            currentElement = this.m_singleResultSelector(mutables.m_currentLeft, mutables.m_currentRightMatches.m_chunk[mutables.m_currentRightMatchesIndex]);
            currentKey     = mutables.m_currentLeftKey;
            mutables.m_currentRightMatchesIndex++;
            return(true);
        }
Exemple #7
0
        public static void RunPlinqModesTests()
        {
            if (Environment.ProcessorCount == 1)
            {
                // Test doesn't apply to DOP == 1.  It verifies that work is actually
                // happening in parallel, which won't be the case with DOP == 1.
                return;
            }

            Action <ParallelExecutionMode, Verifier>[] hardQueries =
            {
                (mode,                                                          verifier) => ParallelEnumerable.Range(0, 1000).WithExecutionMode(mode)
                .Select(x => verifier.Verify(x)).Where(x => true).TakeWhile((x, i) => true).ToArray(),

                (mode,                                                          verifier) => ParallelEnumerable.Range(0, 1000).WithExecutionMode(mode)
                .Select(x => verifier.Verify(x)).Where(x => true).TakeWhile((x, i) => true).Iterate(),

                (mode,                                                          verifier) => ParallelEnumerable.Range(0, 1000).WithExecutionMode(mode)
                .Where(x => true).Select(x => verifier.Verify(x)).ElementAt(5),

                (mode,                                                          verifier) => ParallelEnumerable.Range(0, 1000).WithExecutionMode(mode)
                .Where(x => true).Select((x,                                    i) => verifier.Verify(x)).Iterate(),
            };

            Action <ParallelExecutionMode, Verifier>[] easyQueries =
            {
                (mode,                                                                                   verifier) => ParallelEnumerable.Range(0,                         1000).WithExecutionMode(mode)
                .TakeWhile(x => true).Select(x => verifier.Verify(x)).ToArray(),

                (mode,                                                                                   verifier) => ParallelEnumerable.Range(0,                         1000).WithExecutionMode(mode)
                .TakeWhile(x => true).Select(x => verifier.Verify(x)).Iterate(),

                (mode,                                                                                   verifier) => Enumerable.Range(0,            1000).ToArray().AsParallel()
                .Select(x => verifier.Verify(x)).Take(100).WithExecutionMode(mode).ToArray(),

                (mode,                                                                                   verifier) => Enumerable.Range(0,                                    1000).ToArray().AsParallel().WithExecutionMode(mode)
                .Take(100).Select(x => verifier.Verify(x)).Iterate(),

                (mode,                                                                                   verifier) => ParallelEnumerable.Range(0,                                           1000).WithExecutionMode(mode)
                .Select(x => verifier.Verify(x)).ElementAt(5),

                (mode,                                                                                   verifier) => ParallelEnumerable.Range(0,                                          1000).WithExecutionMode(mode)
                .Select(x => verifier.Verify(x)).SelectMany((x,                                          i) => Enumerable.Repeat(1,                                                                                                                   2)).Iterate(),

                (mode,                                                                                   verifier) => Enumerable.Range(0,                                          1000).AsParallel().WithExecutionMode(mode)
                .Select(x => verifier.Verify(x)).SelectMany((x,                                          i) => Enumerable.Repeat(1,                                                                                                                   2)).Iterate(),

                (mode,                                                                                   verifier) => Enumerable.Range(0,                                              1000).AsParallel().WithExecutionMode(mode).AsUnordered()
                .Select(x => verifier.Verify(x)).Select((x,                                              i) => x).Iterate(),

                (mode,                                                                                   verifier) => Enumerable.Range(0,         1000).AsParallel().WithExecutionMode(mode).AsUnordered().Where(x => true).Select(x => verifier.Verify(x)).First(),

                (mode,                                                                                   verifier) => Enumerable.Range(0,                              1000).AsParallel().WithExecutionMode(mode)
                .Select(x => verifier.Verify(x)).OrderBy(x => x).ToArray(),

                (mode,                                                                                   verifier) => Enumerable.Range(0,                              1000).AsParallel().WithExecutionMode(mode)
                .Select(x => verifier.Verify(x)).OrderBy(x => x).Iterate(),

                (mode,                                                                                   verifier) => Enumerable.Range(0,                                                              1000).AsParallel().AsOrdered().WithExecutionMode(mode)
                .Where(x => true).Select(x => verifier.Verify(x))
                .Concat(Enumerable.Range(0,                                                                               1000).AsParallel().AsOrdered().Where(x => true))
                .ToList(),

                (mode,                                                                                   verifier) => ParallelEnumerable.Range(0,                   1000).WithExecutionMode(mode)
                .Where(x => true).Select(x => verifier.Verify(x)).Take(100).ToArray(),

                (mode,                                                                                   verifier) => ParallelEnumerable.Range(0,                   1000).WithExecutionMode(mode)
                .Where(x => true).Select(x => verifier.Verify(x)).Take(100).Iterate(),

                (mode,                                                                                   verifier) => ParallelEnumerable.Range(0,                         1000).WithExecutionMode(mode)
                .Select(x => verifier.Verify(x)).TakeWhile(x => true).ToArray(),

                (mode,                                                                                   verifier) => ParallelEnumerable.Range(0,                         1000).WithExecutionMode(mode)
                .Select(x => verifier.Verify(x)).TakeWhile(x => true).Iterate(),

                (mode,                                                                                   verifier) => ParallelEnumerable.Range(0,   1000)
                .OrderBy(x => x).Select(x => verifier.Verify(x)).WithExecutionMode(mode).ElementAt(5),

                (mode,                                                                                   verifier) => ParallelEnumerable.Range(0,                                                              1000).WithExecutionMode(mode)
                .OrderBy(x => x).Select((x,                                                              i) => verifier.Verify(x)).Iterate(),

                (mode,                                                                                   verifier) => ParallelEnumerable.Range(0, 1000).WithExecutionMode(mode)
                .Where(x => true).Select(x => verifier.Verify(x)).OrderBy(x => x).Take(10000).Iterate(),
            };

            // Verify that all queries in 'easyQueries' run in parallel in default mode

            for (int i = 0; i < easyQueries.Length; i++)
            {
                Verifier verifier = new ParVerifier();
                easyQueries[i].Invoke(ParallelExecutionMode.Default, verifier);
                if (!verifier.Passed)
                {
                    Assert.True(false, string.Format("Easy query {0} expected to run in parallel in default mode", i));
                }
            }

            // Verify that all queries in 'easyQueries' always run in forced mode
            for (int i = 0; i < easyQueries.Length; i++)
            {
                Verifier verifier = new ParVerifier();
                easyQueries[i].Invoke(ParallelExecutionMode.ForceParallelism, verifier);
                if (!verifier.Passed)
                {
                    Assert.True(false, string.Format("Easy query {0} expected to run in parallel in force-parallelism mode", i));
                }
            }

            // Verify that all queries in 'easyQueries' always run in forced mode
            for (int i = 0; i < hardQueries.Length; i++)
            {
                Verifier verifier = new ParVerifier();
                hardQueries[i].Invoke(ParallelExecutionMode.ForceParallelism, verifier);
                if (!verifier.Passed)
                {
                    Assert.True(false, string.Format("Hard query {0} expected to run in parallel in force-parallelism mode", i));
                }
            }
        }
Exemple #8
0
        public static void Show()
        {
            // AggregateException
            {
                // 并行化 异常会在一个独立的线程抛出 跳过 Catch 代码块导致 程序崩溃
                // AggregateException 捕获全部异常并重新抛给调用者
                try
                {
                    var query = from i in ParallelEnumerable.Range(0, 1000000)
                                select 100 / i;
                    // Enumerate query
                    query.Dump();
                }
                catch (AggregateException aex)
                {
                    foreach (Exception ex in aex.InnerExceptions)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
            // Flatten
            {
                // 消除任意层级的嵌套 展平内部异常列表
                try
                {
                    var query = from i in ParallelEnumerable.Range(0, 1000000)
                                select 100 / i;
                    // Enumerate query
                    query.Dump();
                }
                catch (AggregateException aex)
                {
                    foreach (Exception ex in aex.Flatten().InnerExceptions)
                    {
                        ex.Dump();
                    }
                }
            }
            // Handle
            {
                // 捕获特定异常 重新抛出异常类型
                var parent = Task.Factory.StartNew(() =>
                {
                    // We’ll throw 3 exceptions at once using 3 child tasks:

                    int[] numbers = { 0 };

                    var childFactory = new TaskFactory
                                           (TaskCreationOptions.AttachedToParent, TaskContinuationOptions.None);

                    childFactory.StartNew(() => 5 / numbers[0]);  // Division by zero
                    childFactory.StartNew(() => numbers[1]);      // Index out of range
                    childFactory.StartNew(() => { throw null; }); // Null reference
                });

                try { parent.Wait(); }
                catch (AggregateException aex)
                {
                    aex.Flatten().Handle(ex =>   // Note that we still need to call Flatten
                    {
                        if (ex is DivideByZeroException)
                        {
                            Console.WriteLine("Divide by zero");
                            return(true);                           // This exception is "handled"
                        }
                        if (ex is IndexOutOfRangeException)
                        {
                            Console.WriteLine("Index out of range");
                            return(true); // This exception is "handled"
                        }
                        return(false);    // All other exceptions will get rethrown
                    });
                }
            }
        }
 public static void GroupJoin_ArgumentNullException()
 {
     AssertExtensions.Throws <ArgumentNullException>("outer", () => ((ParallelQuery <int>)null).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i));
     AssertExtensions.Throws <ArgumentNullException>("inner", () => ParallelEnumerable.Range(0, 1).GroupJoin((ParallelQuery <int>)null, i => i, i => i, (i, j) => i));
     AssertExtensions.Throws <ArgumentNullException>("outerKeySelector", () => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), (Func <int, int>)null, i => i, (i, j) => i));
     AssertExtensions.Throws <ArgumentNullException>("innerKeySelector", () => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, (Func <int, int>)null, (i, j) => i));
     AssertExtensions.Throws <ArgumentNullException>("resultSelector", () => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func <int, IEnumerable <int>, int>)null));
     AssertExtensions.Throws <ArgumentNullException>("outer", () => ((ParallelQuery <int>)null).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i, EqualityComparer <int> .Default));
     AssertExtensions.Throws <ArgumentNullException>("inner", () => ParallelEnumerable.Range(0, 1).GroupJoin((ParallelQuery <int>)null, i => i, i => i, (i, j) => i, EqualityComparer <int> .Default));
     AssertExtensions.Throws <ArgumentNullException>("outerKeySelector", () => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), (Func <int, int>)null, i => i, (i, j) => i, EqualityComparer <int> .Default));
     AssertExtensions.Throws <ArgumentNullException>("innerKeySelector", () => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, (Func <int, int>)null, (i, j) => i, EqualityComparer <int> .Default));
     AssertExtensions.Throws <ArgumentNullException>("resultSelector", () => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func <int, IEnumerable <int>, int>)null, EqualityComparer <int> .Default));
 }
Exemple #10
0
 public static void LongCount_None(int count)
 {
     Assert.Equal(0, ParallelEnumerable.Range(0, count).LongCount(i => i == -1));
 }
Exemple #11
0
 public static void Count_One(int count, int position)
 {
     Assert.Equal(Math.Min(1, count), ParallelEnumerable.Range(0, count).Count(i => i == position));
 }
Exemple #12
0
 public static void LongCount_All(int count)
 {
     Assert.Equal(count, ParallelEnumerable.Range(0, count).LongCount());
     Assert.Equal(count, ParallelEnumerable.Range(0, count).LongCount(i => i < count));
 }
Exemple #13
0
 public static void CountLongCount_AggregateException()
 {
     AssertThrows.Wrapped <DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).Count(x => { throw new DeliberateTestException(); }));
     AssertThrows.Wrapped <DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).LongCount(x => { throw new DeliberateTestException(); }));
 }
Exemple #14
0
 public static void WithExecutionMode_Multiple(ParallelExecutionMode first, ParallelExecutionMode second)
 {
     Assert.Throws <InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(first).WithExecutionMode(second));
 }
Exemple #15
0
        public void GeneralTests()
        {
            //test1
            IEnumerable <TestClass> Objects = ParallelEnumerable.Repeat <TestClass>(new TestClass(), 2);

            PetriController <TestClass> pn = new PetriController <TestClass>();

            pn.SetReset(o => { o.Number = 0; o.Word = "aaa"; });

            pn.SetObjects(Objects.ToList());

            pn.AddTransition(o => true, o => o.Number == 0 && o.Word == "aaa", o => { }, o => { o.Number = 1; o.Word = "bbb"; }, ExecutionMode.Synch, 0);
            pn.AddTransition(o => true, o => o.Number == 1 && o.Word == "bbb", o => { }, o => { o.Number = 2; o.Word = "ccc"; }, ExecutionMode.Synch, 0);
            pn.AddGeneralTransition(o => true, o => o.Number == 2 && o.Word == "ccc", o => { }, o => { o.Number = 3; o.Word = "ddd"; }, ExecutionMode.Synch, 0);

            pn.Run();

            Assert.IsTrue(Objects.All(o => o.Number == 3 && o.Word == "ddd"));

            pn.Run();

            Assert.IsTrue(Objects.All(o => o.Number == 3 && o.Word == "ddd"));

            //test2
            Objects = ParallelEnumerable.Repeat <TestClass>(new TestClass(), 2);

            pn = new PetriController <TestClass>();

            pn.SetReset(o => { o.Number = 0; o.Word = "aaa"; });

            pn.SetObjects(Objects.ToList());

            pn.AddTransition(o => true, o => o.Number == 0 && o.Word == "aaa", o => { }, o => { o.Number = 1; o.Word = "bbb"; }, ExecutionMode.Asynch, 0);
            pn.AddTransition(o => true, o => o.Number == 1 && o.Word == "bbb", o => { }, o => { o.Number = 2; o.Word = "ccc"; }, ExecutionMode.Asynch, 0);
            pn.AddGeneralTransition(o => true, o => o.Number == 2 && o.Word == "ccc", o => { }, o => { o.Number = 3; o.Word = "ddd"; }, ExecutionMode.Asynch, 0);

            pn.Run();

            Assert.IsTrue(Objects.All(o => o.Number == 3 && o.Word == "ddd"));

            pn.Run();

            Assert.IsTrue(Objects.All(o => o.Number == 3 && o.Word == "ddd"));

            //test3
            Objects = ParallelEnumerable.Repeat <TestClass>(new TestClass(), 2);

            pn = new PetriController <TestClass>();

            pn.SetReset(o => { o.Number = 0; o.Word = "aaa"; });

            pn.SetObjects(Objects.ToList());

            pn.AddTransition(o => true, o => o.Number == 0 && o.Word == "aaa", o => { }, o => { o.Number = 1; o.Word = "bbb"; }, ExecutionMode.Asynch, 0);
            pn.AddTransition(o => true, o => o.Number == 1 && o.Word == "bbb", o => { }, o => { o.Number = 2; o.Word = "ccc"; }, ExecutionMode.Synch, 0);
            pn.AddGeneralTransition(o => true, o => o.Number == 2 && o.Word == "ccc", o => { }, o => { o.Number = 3; o.Word = "ddd"; }, ExecutionMode.Asynch, 0);
            pn.AddTransition(o => true, o => o.Number == 3 && o.Word == "ddd", o => { }, o => { o.Number = 4; o.Word = "eee"; }, ExecutionMode.Synch, 0);

            pn.Run();

            Assert.IsTrue(Objects.All(o => o.Number == 4 && o.Word == "eee"));

            pn.Run();

            Assert.IsTrue(Objects.All(o => o.Number == 4 && o.Word == "eee"));
        }
Exemple #16
0
        public static IEnumerable <object[]> BinaryCancelingOperators()
        {
            yield return(new object[] { Labeled.Label <Func <ParallelQuery <int>, Action, ParallelQuery <int> > >("Except", (source, cancel) => source.Except(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), new CancelingEqualityComparer <int>(cancel))) });

            yield return(new object[] { Labeled.Label <Func <ParallelQuery <int>, Action, ParallelQuery <int> > >("Except-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).Except(source, new CancelingEqualityComparer <int>(cancel))) });

            yield return(new object[] { Labeled.Label <Func <ParallelQuery <int>, Action, ParallelQuery <int> > >("GroupJoin", (source, cancel) => source.GroupJoin(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), x => x, y => y, (x, g) => x, new CancelingEqualityComparer <int>(cancel))) });

            yield return(new object[] { Labeled.Label <Func <ParallelQuery <int>, Action, ParallelQuery <int> > >("GroupJoin-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).GroupJoin(source, x => x, y => y, (x, g) => x, new CancelingEqualityComparer <int>(cancel))) });

            yield return(new object[] { Labeled.Label <Func <ParallelQuery <int>, Action, ParallelQuery <int> > >("Intersect", (source, cancel) => source.Intersect(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), new CancelingEqualityComparer <int>(cancel))) });

            yield return(new object[] { Labeled.Label <Func <ParallelQuery <int>, Action, ParallelQuery <int> > >("Intersect-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).Intersect(source, new CancelingEqualityComparer <int>(cancel))) });

            yield return(new object[] { Labeled.Label <Func <ParallelQuery <int>, Action, ParallelQuery <int> > >("Join", (source, cancel) => source.Join(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), x => x, y => y, (x, y) => x, new CancelingEqualityComparer <int>(cancel))) });

            yield return(new object[] { Labeled.Label <Func <ParallelQuery <int>, Action, ParallelQuery <int> > >("Join-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).Join(source, x => x, y => y, (x, y) => x, new CancelingEqualityComparer <int>(cancel))) });

            yield return(new object[] { Labeled.Label <Func <ParallelQuery <int>, Action, ParallelQuery <int> > >("Union", (source, cancel) => source.Union(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), new CancelingEqualityComparer <int>(cancel))) });

            yield return(new object[] { Labeled.Label <Func <ParallelQuery <int>, Action, ParallelQuery <int> > >("Union-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).Union(source, new CancelingEqualityComparer <int>(cancel))) });
        }
Exemple #17
0
        public void GeneralStaticEntranceTest()
        {
            int key      = 5;
            var LockDic  = new ConcurrentDictionary <int, bool>();
            var TimerDic = new ConcurrentDictionary <int, Timer>();
            Predicate <TestClass>   SolvePredicate = o => false;
            IEnumerable <TestClass> Objects        = ParallelEnumerable.Repeat <TestClass>(new TestClass(), 10);

            //check without locking
            //(without timer)

            LockDic[key] = false;

            SolvePredicate = o => false;
            bool answerFalse = GeneralTransition <TestClass> .StaticEntrance(Objects, SolvePredicate, LockDic, TimerDic, key);

            Assert.IsFalse(answerFalse);
            Assert.IsFalse(LockDic[key]);

            SolvePredicate = o => true;
            bool answerTrue = GeneralTransition <TestClass> .StaticEntrance(Objects, SolvePredicate, LockDic, TimerDic, key);

            Assert.IsTrue(answerTrue);
            Assert.IsTrue(LockDic[key]);


            //(with timer)
            LockDic[key]  = false;
            TimerDic[key] = new Timer(new TimeSpan(0, 0, 0, 0));

            SolvePredicate = o => false;
            answerFalse    = GeneralTransition <TestClass> .StaticEntrance(Objects, SolvePredicate, LockDic, TimerDic, key);

            Assert.IsFalse(answerFalse);

            SolvePredicate = o => true;
            answerTrue     = GeneralTransition <TestClass> .StaticEntrance(Objects, SolvePredicate, LockDic, TimerDic, key);

            Assert.IsTrue(answerTrue);
            Assert.IsTrue(LockDic[key]);


            //check for locking
            LockDic[key]   = true;
            SolvePredicate = o => true;
            TimerDic[key]  = new Timer(new TimeSpan(0, 0, 0, 0));
            answerFalse    = GeneralTransition <TestClass> .StaticEntrance(Objects, SolvePredicate, LockDic, TimerDic, key);

            Assert.IsFalse(answerFalse);

            //check for timer
            LockDic[key]   = false;
            SolvePredicate = o => true;

            TimerDic[key] = new Timer(new TimeSpan(0, 0, 0, 0, 1000));
            TimerDic[key].Start();
            System.Threading.Thread.Sleep(500);
            answerFalse = GeneralTransition <TestClass> .StaticEntrance(Objects, SolvePredicate, LockDic, TimerDic, key);

            Assert.IsFalse(answerFalse);

            TimerDic[key].Reset();
            int count_before = TimerDic[key].ElapsedTime;

            System.Threading.Thread.Sleep(1500);
            answerTrue = GeneralTransition <TestClass> .StaticEntrance(Objects, SolvePredicate, LockDic, TimerDic, key);

            Assert.IsTrue(answerTrue);
            Assert.IsTrue(TimerDic[key].ElapsedTime < 500);

            //check for start timer
            LockDic[key]   = false;
            SolvePredicate = o => true;
            TimerDic[key]  = new Timer(new TimeSpan(0, 0, 0, 0, 1000));
            GeneralTransition <TestClass> .StaticEntrance(Objects, SolvePredicate, LockDic, TimerDic, key);

            Assert.IsTrue(TimerDic[key].IsRun);
        }
        public static void Range_LastOrDefault(int start, int count)
        {
            ParallelQuery <int> query = ParallelEnumerable.Range(start, count);

            Assert.Equal(count == 0 ? 0 : start + (count - 1), query.LastOrDefault());
        }
Exemple #19
0
 public static void Any_ArgumentNullException()
 {
     AssertExtensions.Throws <ArgumentNullException>("source", () => ((ParallelQuery <bool>)null).Any(x => x));
     AssertExtensions.Throws <ArgumentNullException>("predicate", () => ParallelEnumerable.Empty <bool>().Any(null));
 }
 public static void Range_Exception()
 {
     Assert.Throws <ArgumentOutOfRangeException>(() => ParallelEnumerable.Range(0, -1));
     Assert.Throws <ArgumentOutOfRangeException>(() => ParallelEnumerable.Range(-8, -8));
     Assert.Throws <ArgumentOutOfRangeException>(() => ParallelEnumerable.Range(int.MaxValue, 2));
 }
Exemple #21
0
 public static void Sum_Int_AllNull(int count)
 {
     Assert.Equal(0, ParallelEnumerable.Repeat((int?)null, count).Sum());
     Assert.Equal(0, ParallelEnumerable.Range(0, count).Sum(x => (int?)null));
 }
Exemple #22
0
 public static void DegreeOfParallelism_Multiple()
 {
     Assert.Throws <InvalidOperationException>(() => ParallelEnumerable.Range(0, 2).WithDegreeOfParallelism(2).WithDegreeOfParallelism(2));
 }
        public static void SequenceEqual_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation)
        {
            CancellationTokenSource cs = new CancellationTokenSource();

            cs.Cancel();

            Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).SequenceEqual(ParallelEnumerable.Range(0, 2)));
            Functions.AssertIsCanceled(cs, () => ParallelEnumerable.Range(0, 2).SequenceEqual(operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item)));
        }
Exemple #24
0
        public static void Concat_NotSupportedException()
        {
#pragma warning disable 618
            Assert.Throws <NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Concat(Enumerable.Range(0, 1)));
#pragma warning restore 618
        }
 public static void WithMergeOptions_Multiple(ParallelMergeOptions first, ParallelMergeOptions second)
 {
     Assert.Throws <InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(first).WithMergeOptions(second));
 }
Exemple #26
0
 public static void Concat_ArgumentNullException()
 {
     Assert.Throws <ArgumentNullException>("first", () => ((ParallelQuery <int>)null).Concat(ParallelEnumerable.Range(0, 1)));
     Assert.Throws <ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Concat(null));
 }
Exemple #27
0
        // Should not get the same setting from both operands.
        public static void Except_NoDuplicateSettings()
        {
            CancellationToken t = new CancellationTokenSource().Token;

            Assert.Throws <InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Except(ParallelEnumerable.Range(0, 1).WithCancellation(t)));
            Assert.Throws <InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Except(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1)));
            Assert.Throws <InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Except(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default)));
            Assert.Throws <InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Except(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default)));
        }
Exemple #28
0
        public static void Concat_UnionSources_PrematureMerges()
        {
            const int           ElementCount = 2048;
            ParallelQuery <int> leftQuery    = ParallelEnumerable.Range(0, ElementCount / 4).Union(ParallelEnumerable.Range(ElementCount / 4, ElementCount / 4));
            ParallelQuery <int> rightQuery   = ParallelEnumerable.Range(2 * ElementCount / 4, ElementCount / 4).Union(ParallelEnumerable.Range(3 * ElementCount / 4, ElementCount / 4));

            var results = new HashSet <int>(leftQuery.Concat(rightQuery));

            Assert.Equal(ElementCount, results.Count);
        }
Exemple #29
0
 public static float ScalarProd(float[] X, float[] Y, int N)
 {
     return(ParallelEnumerable.Range(0, N).Sum(i => X[i] * Y[i]));
 }
Exemple #30
0
 public static void Zip_ArgumentNullException()
 {
     Assert.Throws <ArgumentNullException>("first", () => ((ParallelQuery <int>)null).Zip(ParallelEnumerable.Range(0, 1), (x, y) => x));
     Assert.Throws <ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Zip(null, (Func <int, int, int>)((x, y) => x)));
     Assert.Throws <ArgumentNullException>("resultSelector", () => ParallelEnumerable.Range(0, 1).Zip(ParallelEnumerable.Range(0, 1), (Func <int, int, int>)null));
 }