当前位置: 首页>>代码示例>>C#>>正文


C# ParallelOptions类代码示例

本文整理汇总了C#中ParallelOptions的典型用法代码示例。如果您正苦于以下问题:C# ParallelOptions类的具体用法?C# ParallelOptions怎么用?C# ParallelOptions使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ParallelOptions类属于命名空间,在下文中一共展示了ParallelOptions类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SaveItems

        async Task<IDictionary<string, CatalogItemSummary>> SaveItems(Guid commitId, DateTime commitTimeStamp, CancellationToken cancellationToken)
        {
            ConcurrentDictionary<string, CatalogItemSummary> pageItems = new ConcurrentDictionary<string, CatalogItemSummary>();

            ParallelOptions options = new ParallelOptions();
            options.MaxDegreeOfParallelism = _threads;

            var items = _batch.ToArray();

            ConcurrentDictionary<CatalogItem, Uri> tmpPages = new ConcurrentDictionary<CatalogItem, Uri>();

            Parallel.ForEach(items, options, item =>
            {
                Uri resourceUri = null;

                try
                {
                    item.TimeStamp = commitTimeStamp;
                    item.CommitId = commitId;
                    item.BaseAddress = Storage.BaseAddress;

                    Uri catalogPageUri = CreateCatalogPage(item);

                    //CommitItemComplete(catalogPageUri);

                    resourceUri = item.GetItemAddress();

                    if (!tmpPages.TryAdd(item, catalogPageUri))
                    {
                        throw new Exception("duplicate item");
                    }


                    //if (catalogPageUri != null)
                    //{
                    //    Uri indexPageUri = CreateIndexEntry(item, catalogPageUri, commitId, commitTimeStamp);

                    //    CommitItemComplete(catalogPageUri, indexPageUri);
                    //}
                    //else
                    //{
                    //    Debug.Fail("Missing catalog content");
                    //}
                }
                catch (Exception e)
                {
                    throw new Exception(string.Format("item uri: {0}", resourceUri == null ? "none" : resourceUri.AbsoluteUri), e);
                }
            });

            // make sure to commit these in the correct order
            foreach (var item in items)
            {
                Uri pageUri = null;
                tmpPages.TryGetValue(item, out pageUri);
                CommitItemComplete(pageUri);
            }

            return pageItems;
        }
开发者ID:jinujoseph,项目名称:NuGet.Services.Metadata,代码行数:60,代码来源:PageCreator.cs

示例2: Form1

 public Form1()
 {
     InitializeComponent();
     cancellationTokenSource = new CancellationTokenSource();
     options = new ParallelOptions();
     options.CancellationToken = cancellationTokenSource.Token;
 }
开发者ID:Baptista,项目名称:PC,代码行数:7,代码来源:Form1.cs

示例3: Main

	public static void Main ()
	{
		object count_lock = new object ();
		int count = 0;

		ParallelOptions options = new ParallelOptions {
			MaxDegreeOfParallelism = Environment.ProcessorCount * 4,
		};

		Thread t1 = new Thread (() => {
			Parallel.ForEach (UntilTimeout (15 * 1000), options, _ => {
				using (Process p = Process.Start ("cat", "/dev/null")) {
					p.WaitForExit ();
				}

				lock (count_lock) {
					count += 1;

					if (count % (10) == 0)
						Console.Write (".");
					if (count % (10 * 50) == 0)
						Console.WriteLine ();
				}
			});
		});

		t1.Start ();

		while (!t1.Join (0)) {
			try {
				using (Process p = Process.GetProcessById (1));
			} catch (ArgumentException) {
			}
		}
	}
开发者ID:sushihangover,项目名称:playscript,代码行数:35,代码来源:process-unref-race.cs

示例4: Mcsrch

        public Mcsrch(int thread_num)
        {
            infoc = 0;
            stage1 = false;
            brackt = false;
            finit = 0.0;
            dginit = 0.0;
            dgtest = 0.0;
            width = 0.0;
            width1 = 0.0;
            stx = 0.0;
            fx = 0.0;
            dgx = 0.0;
            sty = 0.0;
            fy = 0.0;
            dgy = 0.0;
            stmin = 0.0;
            stmax = 0.0;

#if NO_SUPPORT_PARALLEL_LIB
#else
            parallelOption = new ParallelOptions();
            parallelOption.MaxDegreeOfParallelism = thread_num;
#endif
        }
开发者ID:Corniel,项目名称:CRFSharp,代码行数:25,代码来源:Mcsrch.cs

示例5: DynamicSchedulingAndWorkStealing

        static void DynamicSchedulingAndWorkStealing()
        {
            const int iterations = 10000;

            var options = new ParallelOptions();// { MaxDegreeOfParallelism = -1 };
            var threadsUsed = new ConcurrentDictionary<int, int>();

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

            Parallel.ForEach(Enumerable.Range(1, iterations),
                             options,
                             () => 0L,
                             (val, pls, local) =>
                             {
                                 threadsUsed.TryAdd(Thread.CurrentThread.ManagedThreadId, 0);
                                 if (val < (iterations / 2))
                                 {
                                    //for (int i = 0; i < 1000000; i++) ;
                                    Thread.Sleep(1);
                                 }
                                 return local + 1;
                             },
                             local => Console.WriteLine("Thread {0} processed {1} items", Thread.CurrentThread.ManagedThreadId, local));

            sw.Stop();

            Console.WriteLine("Used {0} different threads and took {1}ms", threadsUsed.Count, sw.ElapsedMilliseconds);
        }
开发者ID:srstrong,项目名称:DDDSW2010,代码行数:29,代码来源:ParallelOptions.cs

示例6: CancellationOfParallelFor

        private static void CancellationOfParallelFor()
        {
            var nums = Enumerable.Range(0, 100000);

            var cts = new CancellationTokenSource();
            var options = new ParallelOptions()
            {
                CancellationToken = cts.Token,
                MaxDegreeOfParallelism = Environment.ProcessorCount
            };

            Console.WriteLine("Press any key to start, Press 'c' to cancel");
            Console.ReadKey();

            Task.Factory.StartNew(() =>
            {
                if (Console.ReadKey().KeyChar == 'c')
                    cts.Cancel();
            });

            try
            {
                Parallel.ForEach(nums, options, num =>
                {
                    var d = Math.Sqrt(num);
                    Console.WriteLine("{0} on {1}", d,
                                      Thread.CurrentThread.ManagedThreadId);
                    options.CancellationToken.ThrowIfCancellationRequested();
                });
            }
            catch (OperationCanceledException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
开发者ID:smwhit,项目名称:Net.Sandbox.Samples,代码行数:35,代码来源:Program.cs

示例7: Foo1

        static void Foo1()
        {
            var list = new List<int>() {10,20,30,40,50 };
            var options = new ParallelOptions();
            var total = 0;
            var result = Parallel.For(0, list.Count,
                () =>
                {
                    Console.WriteLine("Thread");
                    return 1;
                },
                (i, loop, j) =>
                {
                    Console.WriteLine("body");
                    Console.WriteLine("i= " + list[i] + " j=" + j);
                    return list[i];
                },
                (i) =>
                {
                    Console.WriteLine("Foot");
                    Interlocked.Add(ref total,i);
                    Console.WriteLine("total="+total);
                });

            Console.WriteLine(result.IsCompleted);
        }
开发者ID:HK-Zhang,项目名称:Grains,代码行数:26,代码来源:ParallelDemo.cs

示例8: search

        public static Info search(String path, String extension, string predicate)
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            ParallelOptions options = new ParallelOptions();
            options.CancellationToken = cancellationTokenSource.Token;

            Info info = new Info();
            string[] files = Directory.GetFiles(path, extension, SearchOption.AllDirectories);
            info.totalextensions = files.Length;
            ParallelLoopResult loopResult = Parallel.For(
                0,
                files.Length,
                options,
                (i, loopState) =>
                    {
                        if (File.ReadAllText(files[i]).Contains(predicate))
                        {
                            info.names.Add(files[i]);
                        }
                    }
                );
            if (loopResult.IsCompleted)
            {
                info.total = info.names.Count;
                
            }
            return info;
        }
开发者ID:Baptista,项目名称:PC,代码行数:28,代码来源:AsyncFileSearchText.cs

示例9: Start

        /// <summary>
        /// Запускает на выполнение задачу по скачиванию песен и возвращает результат
        /// </summary>
        /// <param name="CancToken">Токен отмены операции</param>
        /// <param name="MaxDegreeOfParallelism">Максимальное количество потоков, которое будет использоваться для запросов к серверу. 
        /// Если меньше 1, ограничение на количество потоков будет снято.</param>
        /// <returns></returns>
        public IDictionary<OneSongHeader, Exception> Start(CancellationToken CancToken, Int32 MaxDegreeOfParallelism)
        {
            if (MaxDegreeOfParallelism < 1) { MaxDegreeOfParallelism = -1; }

            ConcurrentDictionary<OneSongHeader, Exception> intermediate =
                new ConcurrentDictionary<OneSongHeader, Exception>(MaxDegreeOfParallelism, this._songs.Length);
            ParallelOptions opt = new ParallelOptions() { CancellationToken = CancToken, MaxDegreeOfParallelism = MaxDegreeOfParallelism };
            
            try
            {
                ParallelLoopResult p_res = Parallel.ForEach(this._songs, opt,
                (OneSongHeader song, ParallelLoopState pls, Int64 i) =>
                {
                    if (pls.ShouldExitCurrentIteration)
                    {

                        pls.Stop();
                    }
                    KeyValuePair<OneSongHeader, Exception> res =
                        Core.DownloadAndSaveOneSong
                        (song, this._userAgent, this._generateNewFilenames, this._filenameTemplate, this._folderPath, (Int32)i + 1);
                    this.OnNext.Invoke(res.Key, res.Value);
                    intermediate.TryAdd(res.Key, res.Value);
                }
                );
            }
            catch (OperationCanceledException)
            {
                this.OnCancellation(intermediate.Count, this._songs.Length);
                CancToken.ThrowIfCancellationRequested();
            }
            this.OnComplete.Invoke(intermediate);
            return intermediate;
        }
开发者ID:Klotos,项目名称:MyzukaRuGrabber,代码行数:41,代码来源:ReactiveDownloader.cs

示例10: Main

        static void Main(string[] args)
        {
            int start = Environment.TickCount;
            int maxParallelUploads = 50;
            string urlForUploads = "http://localhost:8080";
            string dirToUpload = Path.Combine(".", "default-to-upload");
            if (args.Length > 0)
            {
                dirToUpload = args[0];
            }

            ParallelOptions opts = new ParallelOptions();
            opts.MaxDegreeOfParallelism = maxParallelUploads;

            Parallel.ForEach(Directory.EnumerateFiles(dirToUpload, "*", SearchOption.AllDirectories), opts, (filepath) =>
            {
                Console.WriteLine("Uploading {0} on thread {1}...", filepath, Thread.CurrentThread.ManagedThreadId);
                WebClient webClient = new WebClient();
                int sleepPeriodMs = 1000;
                bool retry = true;
                bool success = false;

                while (retry)
                {
                    retry = false;
                    try
                    {
                        webClient.UploadFile(urlForUploads, filepath);
                        success = true;
                    }
                    catch (WebException e)
                    {
                        var r = (HttpWebResponse)e.Response;
                        if (r != null && r.StatusCode == HttpStatusCode.ServiceUnavailable)
                        {
                            // We are overloading the server. Wait some time and try again.
                            Console.WriteLine("Server is overloaded. Retrying in {0}ms...", sleepPeriodMs);
                            Thread.Sleep(sleepPeriodMs);
                            sleepPeriodMs *= 2;
                            retry = true;
                        }
                        else
                        {
                            Console.WriteLine("Failed to upload file {0}. Error was: \n{1}.\nMoving on to next file.", filepath, e.ToString());
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Unexpected error! Failed to upload file {0}. Moving on to next file.", filepath);
                    }
                }

                if (success)
                {
                    // The file was successfully uploaded to the server - delete it!
                    File.Delete(filepath);
                }
            });
            Console.WriteLine("Took {0} ticks to upload files.", Environment.TickCount - start);
        }
开发者ID:shrike,项目名称:FileUploads,代码行数:60,代码来源:Program.cs

示例11: Main

        static void Main()
        {
            var tokenSource = new CancellationTokenSource();

            var options = new ParallelOptions { CancellationToken = tokenSource.Token };

            ThreadPool.QueueUserWorkItem(obj =>
            {
                try
                {
                    Parallel.For(0, 1000, options, i => DoWork(i, options.CancellationToken));
                }
                catch (OperationCanceledException)
                {
                    Console.WriteLine("Loop operation was cancelled");
                }
            });

            Thread.Sleep(250);

            Console.WriteLine("Cancelling work...");
            tokenSource.Cancel();

            Thread.Sleep(1000);
        }
开发者ID:srstrong,项目名称:DDDSW2010,代码行数:25,代码来源:CooperativeCancellation.cs

示例12: Execute

 private void Execute(IStatSource state, ParallelOptions parallelOptions)
 {
     state.Calculate(parallelOptions.CancellationToken);
     lock (_statLock) {
         _pendingStatJobs--;
     }
 }
开发者ID:serakrin,项目名称:presentations,代码行数:7,代码来源:StatCounter.cs

示例13: SearchBattle

 public void SearchBattle()
 {
     var opt = new ParallelOptions();
     opt.MaxDegreeOfParallelism = 4;
     Parallel.ForEach(Players.Where(p => !p.isBattle).OrderBy(p=>GB.Random.NextDouble()).ToList(), opt, () => new List<Battle>(), (player, pls, battles) =>
     {
         if (Battles.Find(p => p != null && p.CanJoin(player.Udemae) && p.Join(player)) == null)
         {
             if (battles.Find(p => p != null && p.CanJoin(player.Udemae) && p.Join(player)) == null)
             {
                 var battle = new Battle(player.Udemae);
                 lock (this)
                 {
                     battles.Add(battle);
                     battle.Join(player);
                 }
             }
         }
         return battles;
     }
     ,
     (battles) =>
     {
         lock (this)
         {
             Battles.AddRange(battles);
         }
     }
     );
 }
开发者ID:hrhtspr,项目名称:SplatoonSim,代码行数:30,代码来源:Sim.cs

示例14: DoWork

            private void DoWork(object unused)
            {
                try
                {
                    var fileList = GetFiles();
                    var parallelOptions = new ParallelOptions();
                    parallelOptions.CancellationToken = _cancellationToken;
                    parallelOptions.MaxDegreeOfParallelism = Environment.ProcessorCount;

                    Parallel.For(0, fileList.Count, parallelOptions, i =>
                    {
                        string file = fileList[i];
                        IEnumerable<ParseItem> items = GetItems(file, _searchValue);
                        foreach (ParseItem sel in items)
                        {
                            _cancellationToken.ThrowIfCancellationRequested();
                            _navigateToCallback.AddItem(new NavigateToItem(_searchValue, NavigateToItemKind.Field, "CSS", _searchValue, new CssGoToLineTag(sel, file), MatchKind.Exact, _providerFactory));
                        }

                        var backgroundProgress = Interlocked.Increment(ref _backgroundProgress);
                        _navigateToCallback.ReportProgress(backgroundProgress, fileList.Count);
                    });
                }
                catch
                {
                    // Don't let exceptions from the background thread reach the ThreadPool.  Swallow them
                    // here and complete the navigate operation
                }
                finally
                {
                    _navigateToCallback.Done();
                }
            }
开发者ID:Gordon-Beeming,项目名称:WebEssentials2013,代码行数:33,代码来源:CssGoToLineProvider.cs

示例15: GetFixAsync

        public virtual async Task<CodeAction> GetFixAsync(
            ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentsAndDiagnosticsToFixMap,
            FixAllContext fixAllContext)
        {
            if (documentsAndDiagnosticsToFixMap != null && documentsAndDiagnosticsToFixMap.Any())
            {
                fixAllContext.CancellationToken.ThrowIfCancellationRequested();

                var documents = documentsAndDiagnosticsToFixMap.Keys.ToImmutableArray();
                var fixesBag = new List<CodeAction>[documents.Length];
                var options = new ParallelOptions() { CancellationToken = fixAllContext.CancellationToken };
                Parallel.ForEach(documents, options, (document, state, index) =>
                {
                    fixAllContext.CancellationToken.ThrowIfCancellationRequested();
                    fixesBag[index] = new List<CodeAction>();
                    this.AddDocumentFixesAsync(document, documentsAndDiagnosticsToFixMap[document], fixesBag[index].Add, fixAllContext).Wait(fixAllContext.CancellationToken);
                });

                if (fixesBag.Any(fixes => fixes.Count > 0))
                {
                    return await this.TryGetMergedFixAsync(fixesBag.SelectMany(i => i), fixAllContext).ConfigureAwait(false);
                }
            }

            return null;
        }
开发者ID:journeyman,项目名称:StyleCopAnalyzers,代码行数:26,代码来源:CustomBatchFixAllProvider.cs


注:本文中的ParallelOptions类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。