internal Oper(AssocType assoc, TokenType type, int level, ParseDelegate parseFunc = null, CombineDelegate combineFunc = null) : this(assoc, type, level) { if (parseFunc != null) { Parse = parseFunc; } if (combineFunc != null) { Combine = combineFunc; } }
delegate void CombineDelegate(); //объявляю делегат без возврата для задания 2 static void Main(string[] args) { Console.WriteLine("Task 1"); // Задание 1 и 1* BigBadWolf bigWolf = new BigBadWolf(); // Создаю экземпляр класса БольшойСтрашныйВолк Ba wolf = delegate(string name) //Задание 1 - создаю анонимный делегат со входным стрингом и выводом типа БольшойСтрашныйВолк { bigWolf.name = name; return(bigWolf); }; wolf("Jim").tryWoof(); //Использую делегат метода Вуф в используя первый делегат Console.ReadKey(); // Console.WriteLine(); // Задание 2 Console.WriteLine("Task 2"); CombineDelegate One = delegate { Console.WriteLine("One"); }; //Содаю анонимный делегат Один CombineDelegate Two = delegate { Console.WriteLine("Two"); }; //Содаю анонимный делегат Два CombineDelegate Three = delegate { Console.WriteLine("Three"); }; //Содаю анонимный делегат Три CombineDelegate Four = delegate { Console.WriteLine("Four"); }; //Содаю анонимный делегат Четыри CombineDelegate OnePlusTwo = One + Two; //При добавлении 2 делегатов они выполняются поочереди OnePlusTwo(); Console.WriteLine(); CombineDelegate OnePlusTwoAndThree = OnePlusTwo + Three; //Идентичный пример с предыдущим, но добавляется к уже скомбинированому OnePlusTwoAndThree(); Console.WriteLine(); CombineDelegate OnePlusTwoAndThreeMinusOne = OnePlusTwoAndThree - One; //При отнимании отнимании делегат с данным именем удалается со списка воспроизведеия данного делегата OnePlusTwoAndThreeMinusOne(); Console.WriteLine(); CombineDelegate OnePlusTwoMinusFour = OnePlusTwo - Four; //При отнимании несуществующего делегата в данной колекции ничего не происходит OnePlusTwoMinusFour(); Console.ReadKey(); }
private static T ReduceTask <T>(int start, int end, int grainSize, ReduceDelegate <T> loopbody, CombineDelegate <T> combineMethod) { int num = end - start; T result; if (num > grainSize) { int middle = (num / 2) + start; Future <T> task = new DelegateFuture <T>(delegate { return(ReduceTask(start, middle, grainSize, loopbody, combineMethod)); }).Start(); result = ReduceTask(middle, end, grainSize, loopbody, combineMethod); return(combineMethod(result, task.Result())); } // grainSize is never less than 1, thus num cannot be less than one. if (num == 1) { return(loopbody(start)); } result = combineMethod(loopbody(start), loopbody(start + 1)); for (int i = start + 2; i < end; i++) { result = combineMethod(result, loopbody(i)); } return(result); }
/// <summary> /// Calculates and combines values to a single value. /// </summary> /// <remarks> /// Parallel.Reduce combines multiple associative values into a single value. The ReduceDelegate loopbody /// takes an integer between start and end and returns an element of type T. The CombineDelegate takes two such /// elements and combine them. <p/> /// Parallel.Reduce avoids using locks by dividing the problem into a binary task tree where each task /// updates it's own local value.<p/> /// GrainSize specifies a reasonable number of iterations in each task. If the number of iterations is more than grainSize, data /// is split in two and handled separately. /// Adjusting the grain size can lead to better performance, but the optimal grain size depends on the problem at hand. /// Increasing the grain size will decrease the /// amount of tasks, and thus decrease the overhead of setting up tasks. But a small amount of tasks could introduce some load /// balancing problems, if no tasks are available for free processors. Decreasing the grain size will increase the amount of /// tasks and thereby ensure better load balancing, but on the other hand it will also increase the overhead of setting up tasks.<p/> /// Parallel.Reduce catches any uncaught exception raised inside the tasks. Once the exception is caught Parallel.Reduce cancels all /// running tasks that it has started and throws a Jibu.CancelException, containing the original exception. Jibu cancels all /// tasks but it doesn't just brutally stop them - the user defined code must detect and handle the cancellation. For more information on cancellation see Jibu.Task.Cancel and Jibu.CancelException /// </remarks> /// <exception cref="Jibu.CancelException">If one of the Tasks is cancelled, Parallel.Reduce cancels the remaining Tasks /// and throws a Jibu.CancelException.</exception> /// <exception cref="System.ArgumentOutOfRangeException">Is thrown if the grain size is less than 1.</exception> /// <typeparam name="T">A type that must be associative</typeparam> /// <param name="start">First index, which is incremented by one until it equals end.</param> /// <param name="end">Last index, which is not included in the loop. The loop runs as long as start is less than end.</param> /// <param name="initialValue">The initial value for the result.</param> /// <param name="grainSize">A reasonable number of iterations in each task</param> /// <param name="loopbody">A delegate containing the work. Loopbody is executed once for each iteration.</param> /// <param name="combineMethod">A delegate used to combine the local results</param> /// <returns>A single value of type T</returns> // <example> // - Parallel Reduce Example - // <code><include ReduceExample/ReduceExample.cs></code> // </example> public static T Reduce <T>(int start, int end, T initialValue, int grainSize, ReduceDelegate <T> loopbody, CombineDelegate <T> combineMethod) { if (end - start < 1) { return(initialValue); } if (grainSize < 1) { throw new ArgumentOutOfRangeException("Grain size cannot be less than 1."); } return(new DelegateFuture <T>(delegate { return combineMethod(initialValue, ReduceTask <T>(start, end, grainSize, loopbody, combineMethod)); }).Result()); }
/// <summary> /// Calculates and combines values to a single value. /// </summary> /// <remarks> /// Parallel.Reduce combines multiple associative values into a single value. The ReduceDelegate loopbody /// takes an integer between start and end and returns an element of type T. The CombineDelegate takes two such /// elements and combine them. <p/> /// Parallel.Reduce avoids using locks by dividing the problem into a binary task tree where each task /// updates it's own local value.<p/> /// Grain size is implicit set to two. It's often possible to increase performance by adjusting the grain size. /// To do so use Parallel.Reduce(int start, int end, T initialValue, int grainSize, ReduceDelegate loopbody, CombineDelegate combineMethod). /// Parallel.<p/> /// Reduce catches any uncaught exception raised inside the tasks. Once the exception is caught Parallel.Reduce cancels all /// running tasks that it has started and throws a Jibu.CancelException, containing the original exception. Jibu cancels all /// tasks but it doesn't just brutally stop them - the user defined code must detect and handle the cancellation. For more information on cancellation see Jibu.Task.Cancel and Jibu.CancelException /// </remarks> /// <exception cref="Jibu.CancelException">If one of the Tasks is cancelled, Parallel.Reduce cancels the remaining Tasks /// and throws a Jibu.CancelException.</exception> /// <typeparam name="T">A type that must be associative</typeparam> /// <param name="start">First index, which is incremented by one until it equals end.</param> /// <param name="end">Last index, which is not included in the loop. The loop runs as long as start is less than end.</param> /// <param name="initialValue">The initial value for the result.</param> /// <param name="loopbody">A delegate containing the work. Loopbody is executed once for each iteration.</param> /// <param name="combineMethod">A delegate used to combine the local results</param> /// <returns>A single value of type T</returns> // <example> // - Parallel Reduce Example - // <code><include ReduceExample/ReduceExample.cs></code> // </example> public static T Reduce <T>(int start, int end, T initialValue, ReduceDelegate <T> loopbody, CombineDelegate <T> combineMethod) { return(Reduce(start, end, initialValue, 1, loopbody, combineMethod)); }
internal Oper(AssocType assoc, TokenType type, int level) { this.assoc = assoc; this.type = type; this.level = level; switch (assoc) { case AssocType.BinaryLeft: case AssocType.BinaryRight: switch (type) { case TokenType.GT: Parse = _parse_gt; break; case TokenType.LT: Parse = _parse_lt; break; default: Parse = _parse; break; } Combine = _combine_binary; break; case AssocType.PostfixDot: this.assoc = AssocType.Postfix; Parse = _parse_postfix_dot; Combine = _combine_postfix_dot; break; case AssocType.PostfixColon: this.assoc = AssocType.Postfix; Parse = _parse_postfix_colon; Combine = _combine_postfix_colon; break; case AssocType.BinaryDot: this.assoc = AssocType.BinaryLeft; Parse = _parse; Combine = _combine_binary_dot; break; case AssocType.BinaryColon: this.assoc = AssocType.BinaryLeft; Parse = _parse; Combine = _combine_binary_colon; break; case AssocType.PostfixCall: this.assoc = AssocType.Postfix; Parse = _parse_postfix_call; Combine = _combine_postfix_call; break; case AssocType.PostfixIndex: this.assoc = AssocType.Postfix; Parse = _parse_postfix_index; Combine = _combine_postfix_index; break; case AssocType.BinaryAssign: this.assoc = AssocType.BinaryRight; Parse = _parse; Combine = _combine_binary_assign; break; case AssocType.BinaryAssignOp: this.assoc = AssocType.BinaryRight; Parse = _parse; Combine = _combine_binary_assign_op; break; case AssocType.BinaryLogic: this.assoc = AssocType.BinaryLeft; Parse = _parse; Combine = _combine_binary_logic; break; case AssocType.Postfix: Parse = _parse; Combine = _combine_postfix; break; case AssocType.Prefix: Parse = _parse; Combine = _combine_prefix; break; case AssocType.PostfixAssign: this.assoc = AssocType.Postfix; Parse = _parse; Combine = _combine_postfix_assign; break; case AssocType.PrefixAssign: this.assoc = AssocType.Prefix; Parse = _parse; Combine = _combine_prefix_assign; break; case AssocType.PostfixIs: this.assoc = AssocType.Postfix; Parse = _parse_is_as; Combine = _combine_postfix_is; break; case AssocType.PostfixAsType: this.assoc = AssocType.Postfix; Parse = _parse_is_as; Combine = _combine_postfix_as_type; break; case AssocType.PrefixCast: this.assoc = AssocType.Prefix; Parse = _parse; Combine = _combine_prefix_cast; break; case AssocType.PrefixRuntimeId: this.assoc = AssocType.Prefix; Parse = _parse; Combine = _combine_prefix_runtime_id; break; case AssocType.BinaryAlias: this.assoc = AssocType.BinaryLeft; Parse = _parse_alias; Combine = _combine_binary_alias; break; case AssocType.BinarySubstr: this.assoc = AssocType.BinaryLeft; Parse = _parse; Combine = _combine_binary_substr; break; case AssocType.None: Parse = _parse_empty; Combine = null; break; } }