本文整理汇总了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;
}
示例2: Form1
public Form1()
{
InitializeComponent();
cancellationTokenSource = new CancellationTokenSource();
options = new ParallelOptions();
options.CancellationToken = cancellationTokenSource.Token;
}
示例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) {
}
}
}
示例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
}
示例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);
}
示例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);
}
}
示例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);
}
示例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;
}
示例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;
}
示例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);
}
示例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);
}
示例12: Execute
private void Execute(IStatSource state, ParallelOptions parallelOptions)
{
state.Calculate(parallelOptions.CancellationToken);
lock (_statLock) {
_pendingStatJobs--;
}
}
示例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);
}
}
);
}
示例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();
}
}
示例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;
}