Exemplo n.º 1
0
        /// <include file='../../_Doc/mscorlib.xml' path='doc/members/member[@name="M:System.Threading.Tasks.Parallel.ForEach``1(System.Collections.Concurrent.Partitioner{``0},System.Threading.Tasks.ParallelOptions,System.Action{``0,System.Threading.Tasks.ParallelLoopState})"]/*' />
        public static ParallelLoopResult ForEach <TSource>(
            Partitioner <TSource> source,
            ParallelOptions parallelOptions,
            Action <TSource, ParallelLoopState> body)
        {
            var loopState = new ParallelLoopState();

            foreach (var partition in source.GetPartitions(1))
            {
                while (partition.MoveNext())
                {
                    if (loopState.ShouldExitCurrentIteration)
                    {
                        return new ParallelLoopResult {
                                   IsCompleted = false, LowestBreakIteration = null
                        }
                    }
                    ;

                    body(partition.Current, loopState);
                }
            }

            return(new ParallelLoopResult {
                IsCompleted = true
            });
        }

        #endregion
    }
Exemplo n.º 2
0
 private static void ShrinkFile(string filename, ParallelLoopState arg2, long arg3)
 {
     FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
     Image img = new Image(fs);
     var wpercent = (300 / img.Width);
     var hsize = img.Height * wpercent;
 }
Exemplo n.º 3
0
        int DoExecute(IGrouping <string, ITaskItem> imageGroup, ThreadingTasks.ParallelLoopState state, int loop)
        {
            var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            Directory.CreateDirectory(tempDirectory);
            var tempOutputDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            Directory.CreateDirectory(tempOutputDirectory);
            try {
                LogDebugMessage("Crunch Processing : {0}", imageGroup.Key);
                LogDebugTaskItems("  Items :", imageGroup.ToArray());
                foreach (var item in imageGroup)
                {
                    var dest = Path.GetFullPath(item.ItemSpec).Replace(imageGroup.Key, tempDirectory);
                    Directory.CreateDirectory(Path.GetDirectoryName(dest));
                    MonoAndroidHelper.CopyIfChanged(item.ItemSpec, dest);
                    MonoAndroidHelper.SetWriteable(dest);
                }

                // crunch them
                if (!RunAapt(GenerateCommandLineCommands(tempDirectory, tempOutputDirectory)))
                {
                    return(0);
                }

                // copy them back
                foreach (var item in imageGroup)
                {
                    var dest            = Path.GetFullPath(item.ItemSpec).Replace(imageGroup.Key, tempOutputDirectory);
                    var srcmodifiedDate = File.GetLastWriteTimeUtc(item.ItemSpec);
                    if (!File.Exists(dest))
                    {
                        continue;
                    }
                    MonoAndroidHelper.CopyIfChanged(dest, item.ItemSpec);
                    MonoAndroidHelper.SetWriteable(dest);
                    // reset the Dates so MSBuild/xbuild doesn't think they changed.
                    MonoAndroidHelper.SetLastAccessAndWriteTimeUtc(item.ItemSpec, srcmodifiedDate, Log);
                }
            }
            finally {
                Directory.Delete(tempDirectory, recursive: true);
                Directory.Delete(tempOutputDirectory, recursive: true);
            }
            return(0);
        }
Exemplo n.º 4
0
        /// <include file='../../_Doc/mscorlib.xml' path='doc/members/member[@name="M:System.Threading.Tasks.Parallel.For(System.Int32,System.Int32,System.Action{System.Int32,System.Threading.Tasks.ParallelLoopState})"]/*' />
        public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action <int, ParallelLoopState> body)
        {
            var loopState = new ParallelLoopState();

            for (var i = fromInclusive; i < toExclusive; ++i)
            {
                if (loopState.ShouldExitCurrentIteration)
                {
                    return new ParallelLoopResult {
                               IsCompleted = false, LowestBreakIteration = null
                    }
                }
                ;
                body(i, loopState);
            }
            return(new ParallelLoopResult {
                IsCompleted = true
            });
        }
Exemplo n.º 5
0
        int DoExecute(ITaskItem manifestFile, ThreadingTasks.ParallelLoopState state, int loop)
        {
            if (!File.Exists(manifestFile.ItemSpec))
            {
                LogDebugMessage("{0} does not exists. Skipping", manifestFile.ItemSpec);
                return(0);
            }

            bool upToDate = ManifestIsUpToDate(manifestFile.ItemSpec);

            if (AdditionalAndroidResourcePaths != null)
            {
                foreach (var dir in AdditionalAndroidResourcePaths)
                {
                    if (!string.IsNullOrEmpty(dir.ItemSpec))
                    {
                        upToDate = upToDate && ManifestIsUpToDate(string.Format("{0}{1}{2}{3}{4}", dir, Path.DirectorySeparatorChar, "manifest", Path.DirectorySeparatorChar, "AndroidManifest.xml"));
                    }
                }
            }

            if (upToDate)
            {
                LogMessage("  Additional Android Resources manifsets files are unchanged. Skipping.");
                return(0);
            }

            var defaultAbi = new string [] { null };
            var abis       = SupportedAbis?.Split(new char [] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var abi in (CreatePackagePerAbi && abis?.Length > 1) ? defaultAbi.Concat(abis) : defaultAbi)
            {
                var currentResourceOutputFile = abi != null?string.Format("{0}-{1}", ResourceOutputFile, abi) : ResourceOutputFile;

                if (!ExecuteForAbi(GenerateCommandLineCommands(manifestFile.ItemSpec, abi, currentResourceOutputFile), currentResourceOutputFile))
                {
                    Cancel();
                }
            }

            return(0);
        }
Exemplo n.º 6
0
        /// <include file='../../_Doc/mscorlib.xml' path='doc/members/member[@name="M:System.Threading.Tasks.Parallel.For``1(System.Int32,System.Int32,System.Threading.Tasks.ParallelOptions,System.Func{``0},System.Func{System.Int32,System.Threading.Tasks.ParallelLoopState,``0,``0},System.Action{``0})"]/*' />
        public static ParallelLoopResult For <TLocal>(int fromInclusive, int toExclusive, ParallelOptions parallelOptions,
                                                      Func <TLocal> localInit, Func <int, ParallelLoopState, TLocal, TLocal> body, Action <TLocal> localFinally)
        {
            var loopState = new ParallelLoopState();

            for (var i = fromInclusive; i < toExclusive; ++i)
            {
                if (loopState.ShouldExitCurrentIteration)
                {
                    return new ParallelLoopResult {
                               IsCompleted = false, LowestBreakIteration = null
                    }
                }
                ;
                localFinally(body(i, loopState, localInit()));
            }
            return(new ParallelLoopResult {
                IsCompleted = true
            });
        }
Exemplo n.º 7
0
		private void ProcessXPSFile(FileInfo xpsF, ParallelLoopState pls, long l)
		{
			Log("Processing: " + xpsF.Name);
			string xpsFileName = xpsF.FullName;

			try
			{

				XpsDocument xpsDoc = new XpsDocument(xpsFileName, System.IO.FileAccess.Read);

				System.Threading.ParameterizedThreadStart ts = new System.Threading.ParameterizedThreadStart(ProcessXPSonSTA);
				System.Threading.Thread tProcess = new System.Threading.Thread(ts);
				tProcess.SetApartmentState(System.Threading.ApartmentState.STA);
				tProcess.Start(new XPSParams() { xpsFileName = xpsFileName, xpsDoc = xpsDoc });
			}
			catch (Exception e)
			{
				Log(e.ToString());
			}
		}
Exemplo n.º 8
0
        private void CalculateImage(ImageViewModel imageViewModel, ParallelLoopState state, Int64 counter)
        {
            if (DoRestart) state.Stop();

            var messageText = "Calculating Compressed Size" +
                              new string('.', (int)(counter % 4));

            if (Application.Current == null) return;

            Application.Current.Dispatcher.Invoke(
                DispatcherPriority.Normal,
                (Action)(() =>
                {
                    Ui.ProgressValue += 1;
                    Ui.MessageText = messageText;
                }));

            lock (_lockObject)
            {
                _sizeSum += ImageModel.GetFileSizeScaledInMegaByte(imageViewModel);
            }
        }
Exemplo n.º 9
0
        private void RenderTile(Tuple<int, int> range, ParallelLoopState state)
        {
            _loger.Log(Level.Verbose, string.Format("Started tile {0} {1}", range.Item1, range.Item2));

            int height = _scene.Camera.Height;

            Bitmap buffer = new Bitmap(range.Item2 - range.Item1, height);

            for (int x = range.Item1; x < range.Item2; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    var finalColor = _rayTracer.CalculatePixelColor(x, y);
                    SetPixelColor(x - range.Item1, y, finalColor, buffer);
                }
            }

            CopyBitmap(buffer, _bitmap, range.Item1);

            _pictureBox.Manipulate(p => p.Refresh());

            _loger.Log(Level.Verbose, string.Format("Finished {0} {1}", range.Item1, range.Item2));
        }
Exemplo n.º 10
0
        static ParallelLoopResult ForEach <TSource, TLocal> (Func <int, IList <IEnumerator <TSource> > > enumerable, ParallelOptions options,
                                                             Func <TLocal> init, Func <TSource, ParallelLoopState, TLocal, TLocal> action,
                                                             Action <TLocal> destruct)
        {
            if (enumerable == null)
            {
                throw new ArgumentNullException("source");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }
            if (init == null)
            {
                throw new ArgumentNullException("init");
            }
            if (destruct == null)
            {
                throw new ArgumentNullException("destruct");
            }

            int num = Math.Min(GetBestWorkerNumber(options.TaskScheduler),
                               options != null && options.MaxDegreeOfParallelism != -1 ? options.MaxDegreeOfParallelism : int.MaxValue);

            Task[] tasks = new Task[num];
            ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos();

            SimpleConcurrentBag <TSource> bag = new SimpleConcurrentBag <TSource> (num);
            const int bagCount = 5;

            IList <IEnumerator <TSource> > slices = enumerable(num);

            int sliceIndex = -1;

            Action workerMethod = delegate {
                IEnumerator <TSource> slice = slices[Interlocked.Increment(ref sliceIndex)];

                TLocal            local = init();
                ParallelLoopState state = new ParallelLoopState(infos);
                int workIndex           = bag.GetNextIndex();
                CancellationToken token = options.CancellationToken;

                try {
                    bool    cont = true;
                    TSource element;

                    while (cont)
                    {
                        if (infos.IsStopped || infos.IsBroken.Value)
                        {
                            return;
                        }

                        token.ThrowIfCancellationRequested();

                        for (int i = 0; i < bagCount && (cont = slice.MoveNext()); i++)
                        {
                            bag.Add(workIndex, slice.Current);
                        }

                        for (int i = 0; i < bagCount && bag.TryTake(workIndex, out element); i++)
                        {
                            if (infos.IsStopped)
                            {
                                return;
                            }

                            token.ThrowIfCancellationRequested();

                            local = action(element, state, local);
                        }
                    }

                    while (bag.TrySteal(workIndex, out element))
                    {
                        token.ThrowIfCancellationRequested();

                        local = action(element, state, local);

                        if (infos.IsStopped || infos.IsBroken.Value)
                        {
                            return;
                        }
                    }
                } finally {
                    destruct(local);
                }
            };

            InitTasks(tasks, num, workerMethod, options);

            try {
                Task.WaitAll(tasks);
            } catch {
                HandleExceptions(tasks, infos);
            }

            return(new ParallelLoopResult(infos.LowestBreakIteration, !(infos.IsStopped || infos.IsExceptional)));
        }
Exemplo n.º 11
0
 public abstract void ParallelLoopBody(string str, ParallelLoopState state, long i);
Exemplo n.º 12
0
        private void RenderToImage(int layerIndex, ParallelLoopState pls)
        {
            if (pls.ShouldExitCurrentIteration)
                return;

            var layer = _layers[layerIndex];
            if (layer.Enabled)
            {
                if (layer.MaxVisible >= _map.Zoom && layer.MinVisible < _map.Zoom)
                {
                    var image = _images[layerIndex] = new Bitmap(_map.Size.Width, _map.Size.Height, PixelFormat.Format32bppArgb);
                    using (IGraphics g = Graphics.FromImage(image).G())
                    {
                        g.PageUnit = GraphicsUnitType.Pixel;
                        ApplyTransform(_transform, g);

                        g.Clear(Color.Transparent);
                        layer.Render(g, _map);
                    }
                }
            }
        }
Exemplo n.º 13
0
        public static ParallelLoopResult For <TLocal> (int from,
                                                       int to,
                                                       ParallelOptions options,
                                                       Func <TLocal> init,
                                                       Func <int, ParallelLoopState, TLocal, TLocal> action,
                                                       Action <TLocal> destruct)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }
            if (init == null)
            {
                throw new ArgumentNullException("localInit");
            }
            if (destruct == null)
            {
                throw new ArgumentNullException("localFinally");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (from >= to)
            {
                return(new ParallelLoopResult(null, true));
            }

            // Number of task to be launched (normally == Env.ProcessorCount)
            int step;
            int num = GetBestWorkerNumber(from, to, options, out step);

            Task[] tasks = new Task [num];

            StealRange[] ranges = new StealRange[num];
            for (int i = 0; i < num; i++)
            {
                ranges[i] = new StealRange(from, i, step);
            }

            ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos();

            int currentIndex = -1;

            Action workerMethod = delegate {
                int        localWorker = Interlocked.Increment(ref currentIndex);
                StealRange range       = ranges[localWorker];
                int        index       = range.Actual;
                int        stopIndex   = localWorker + 1 == num ? to : Math.Min(to, index + step);
                TLocal     local       = init();

                ParallelLoopState state = new ParallelLoopState(infos);
                CancellationToken token = options.CancellationToken;

                try {
                    for (int i = index; i < stopIndex; range.Actual = ++i)
                    {
                        if (infos.IsStopped)
                        {
                            return;
                        }

                        token.ThrowIfCancellationRequested();

                        if (infos.LowestBreakIteration != null && infos.LowestBreakIteration > i)
                        {
                            return;
                        }

                        state.CurrentIteration = i;
                        local = action(i, state, local);
                        if (i >= stopIndex - range.Stolen)
                        {
                            break;
                        }
                    }

                    // Try to steal from our right neighbor (cyclic)
                    int len = num + localWorker;
                    for (int sIndex = localWorker + 1; sIndex < len; ++sIndex)
                    {
                        int extWorker = sIndex % num;
                        range = ranges[extWorker];

                        stopIndex = extWorker + 1 == num ? to : Math.Min(to, from + (extWorker + 1) * step);

                        int stolen;
                        do
                        {
                            stolen = range.Stolen;
                            if (stopIndex - stolen > range.Actual)
                            {
                                goto next;
                            }
                        } while (Interlocked.CompareExchange(ref range.Stolen, stolen + 1, stolen) != stolen);

                        stolen = stopIndex - stolen - 1;

                        if (stolen > range.Actual)
                        {
                            local = action(stolen, state, local);
                        }

next:
                        continue;
                    }
                } finally {
                    destruct(local);
                }
            };

            InitTasks(tasks, num, workerMethod, options);

            try {
                Task.WaitAll(tasks);
            } catch {
                HandleExceptions(tasks, infos);
            }

            return(new ParallelLoopResult(infos.LowestBreakIteration, !(infos.IsStopped || infos.IsExceptional)));
        }
Exemplo n.º 14
0
        private void RenderToImage(int layerIndex, ParallelLoopState pls)
        {
            if (pls.ShouldExitCurrentIteration)
                return;

            var layer = _layers[layerIndex];
            
            if (layer.Enabled)
            {
                double compare = layer.VisibilityUnits == VisibilityUnits.ZoomLevel ? _map.Zoom : _map.MapScale;
                if (layer.MaxVisible >= compare && layer.MinVisible < compare)
                {
                    var image = _images[layerIndex] = new Bitmap(_map.Size.Width, _map.Size.Height, PixelFormat.Format32bppArgb);
                    using (var g = Graphics.FromImage(image))
                    {
                        g.PageUnit = GraphicsUnit.Pixel;
                        ApplyTransform(_transform, g);

                        g.Clear(Color.Transparent);
                        RenderLayer(layer, g, _map);
                    }
                }
            }
        }
Exemplo n.º 15
0
        void CheckAndAddAssambly(string filename, ParallelLoopState state)
        {
            AssemblyName assemblyName = null;

            try
            {
                assemblyName = AssemblyName.GetAssemblyName(filename);
            }
            catch (ArgumentException e)
            {
                IsHandeld(e, filename);
                return;
            }
            catch (BadImageFormatException e)
            {
                IsHandeld(e, filename);
                return;
            }
            catch (FileLoadException e)
            {
                IsHandeld(e, filename);
                return;
            }
            catch (FileNotFoundException e)
            {
                IsHandeld(e, filename);
                return;
            }
            catch (PlatformNotSupportedException e)
            {
                IsHandeld(e, filename);
                return;
            }
            catch (SecurityException e)
            {
                IsHandeld(e, filename);
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine("first chance exception of type '" + e.GetType().ToString() + "' in assambly '" + filename + "' was NOT Handeled by StrongNameCatalog ...");
                state.Stop();
            }

            if (assemblyName == null)
                return;
            #if (SECLOADING)
                                    var publicKey = assemblyName.GetPublicKey();

                                    if (publicKey == null)
                                        continue;

                                    var trusted = _trustedKeys.Any(trustedKey => assemblyName.GetPublicKey().SequenceEqual(trustedKey));

                                    if (!trusted)
                                        continue;
            #endif
            try
            {
                var assam = new AssemblyCatalog(filename);

                if (!assam.Parts.Any())
                    return;

                if (Changing != null)
                    Changing.Invoke(this, new ComposablePartCatalogChangeEventArgs(assam.Parts, new List<ComposablePartDefinition>(), null));

                _aggregateCatalog.Catalogs.Add(assam);
                ImportPool.AddSuccessIncludedMessage(filename);

                if (Changed != null)
                    Changed.Invoke(this, new ComposablePartCatalogChangeEventArgs(assam.Parts, new List<ComposablePartDefinition>(), null));

            }
            catch (Exception e)
            {
                IsHandeld(e, filename);
                return;
            }
        }
Exemplo n.º 16
0
 /// <summary>
 /// Communicates that parallel tasks should stop when they reach a specified iteration element.
 /// (which is CurrentIteration of the caller).
 /// </summary>
 /// <exception cref="T:System.InvalidOperationException">Break() called after Stop().</exception>
 /// <remarks>
 /// Atomically sets shared StoppedBroken flag to BROKEN, then atomically sets shared
 /// LowestBreakIteration to CurrentIteration, but only if CurrentIteration is less than
 /// LowestBreakIteration.
 /// </remarks>
 internal override void InternalBreak()
 {
     ParallelLoopState.Break(CurrentIteration, m_sharedParallelStateFlags);
 }
Exemplo n.º 17
0
        public static ParallelLoopResult For <TLocal> (int fromInclusive,
                                                       int toExclusive,
                                                       ParallelOptions parallelOptions,
                                                       Func <TLocal> localInit,
                                                       Func <int, ParallelLoopState, TLocal, TLocal> body,
                                                       Action <TLocal> localFinally)
        {
            if (body == null)
            {
                throw new ArgumentNullException("body");
            }
            if (localInit == null)
            {
                throw new ArgumentNullException("localInit");
            }
            if (localFinally == null)
            {
                throw new ArgumentNullException("localFinally");
            }
            if (parallelOptions == null)
            {
                throw new ArgumentNullException("options");
            }
            if (fromInclusive >= toExclusive)
            {
                return(new ParallelLoopResult(null, true));
            }

            // Number of task toExclusive be launched (normally == Env.ProcessorCount)
            int step;
            int num = GetBestWorkerNumber(fromInclusive, toExclusive, parallelOptions, out step);

            Task[] tasks = new Task [num];

            StealRange[] ranges = new StealRange[num];
            for (int i = 0; i < num; i++)
            {
                ranges[i] = new StealRange(fromInclusive, i, step);
            }

            ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos();

            int currentIndex = -1;

            Action workerMethod = delegate {
                int        localWorker = Interlocked.Increment(ref currentIndex);
                StealRange range       = ranges[localWorker];
                int        index       = range.V64.Actual;
                int        stopIndex   = localWorker + 1 == num ? toExclusive : Math.Min(toExclusive, index + step);
                TLocal     local       = localInit();

                ParallelLoopState state = new ParallelLoopState(infos);
                CancellationToken token = parallelOptions.CancellationToken;

                try {
                    for (int i = index; i < stopIndex;)
                    {
                        if (infos.IsStopped)
                        {
                            return;
                        }

                        token.ThrowIfCancellationRequested();

                        if (i >= stopIndex - range.V64.Stolen)
                        {
                            break;
                        }

                        if (infos.LowestBreakIteration != null && infos.LowestBreakIteration > i)
                        {
                            return;
                        }

                        state.CurrentIteration = i;
                        local = body(i, state, local);

                        if (i + 1 >= stopIndex - range.V64.Stolen)
                        {
                            break;
                        }

                        range.V64.Actual = ++i;
                    }

                    bool sixtyfour = IntPtr.Size == 8;                     // Environment.Is64BitProcess;

                    // Try toExclusive steal fromInclusive our right neighbor (cyclic)
                    int len = num + localWorker;
                    for (int sIndex = localWorker + 1; sIndex < len; ++sIndex)
                    {
                        int extWorker = sIndex % num;
                        range = ranges[extWorker];

                        stopIndex = extWorker + 1 == num ? toExclusive : Math.Min(toExclusive, fromInclusive + (extWorker + 1) * step);
                        int stolen = -1;

                        do
                        {
                            do
                            {
                                long         old;
                                StealValue64 val = new StealValue64();

                                old       = sixtyfour ? range.V64.Value : Interlocked.CompareExchange(ref range.V64.Value, 0, 0);
                                val.Value = old;

                                if (val.Actual >= stopIndex - val.Stolen - 2)
                                {
                                    goto next;
                                }
                                stolen = (val.Stolen += 1);

                                if (Interlocked.CompareExchange(ref range.V64.Value, val.Value, old) == old)
                                {
                                    break;
                                }
                            } while (true);

                            stolen = stopIndex - stolen;

                            if (stolen > range.V64.Actual)
                            {
                                local = body(stolen, state, local);
                            }
                            else
                            {
                                break;
                            }
                        } while (true);

next:
                        continue;
                    }
                } finally {
                    localFinally(local);
                }
            };

            InitTasks(tasks, num, workerMethod, parallelOptions);

            try {
                Task.WaitAll(tasks);
            } catch {
                HandleExceptions(tasks, infos);
            }

            return(new ParallelLoopResult(infos.LowestBreakIteration, !(infos.IsStopped || infos.IsExceptional)));
        }
Exemplo n.º 18
0
 public override void ParallelLoopBody(string str, ParallelLoopState state, long i)
 {
     this.buffer[i] = base.Replacer.Replace(str);
 }