[英]C# - Linq MultiThreading with varying Max/Min Threads?
ThreadPool.SetMinThreads(50, 50);
ServicePointManager.MaxServicePointIdleTime = 8000;
ServicePointManager.DefaultConnectionLimit = 50;
List<Match> Combos = new Regex("^(.{5,}):(.{6,})$", RegexOptions.Multiline).Matches(File.ReadAllText(ofd.FileNames[0])).OfType<Match>().ToList();
var query = Combos.ToObservable().SelectMany(s => Observable.Start(() => new
{
grab = checkall(s.Groups[1].Value.Replace("\n", "").Replace("\r", ""), s.Groups[2].Value.Replace("\n", "").Replace("\r", ""))
})).ObserveOn(this).Do(x =>
{
try
{
TotalChecked.Text = "Tested: " + (int.Parse(TotalChecked.Text.Substring(7)) + 1).ToString();
progressBar2.Value = (int)Math.Round((double)(100 * int.Parse(TotalChecked.Text.Substring(7))) / Combos.Count);
}
catch (Exception)
{
TotalChecked.Text = "Tested: " + (int.Parse(TotalChecked.Text.Substring(7)) + 1).ToString();
progressBar2.Value = (int)Math.Round((double)(100 * int.Parse(TotalChecked.Text.Substring(7))) / Combos.Count);
}
});
query.ToArray().ObserveOn(this).Subscribe(x =>
{
CheckButton.Location = new Point(CheckButton.Location.X + 31, 9);
CheckButton.Width -= 31;
});
上面的代碼在文本文件上使用正則表達式,然后執行一個函數。 它工作正常,但現在我希望它執行多個DIFFERENT函數,並且只允許其中一些線程設置一定數量的線程。
例如:
var query = Combos.ToObservable().SelectMany(s => Observable.Start(() => new
{
grab = checkall(s.Groups[1].Value.Replace("\n", "").Replace("\r", ""), s.Groups[2].Value.Replace("\n", "").Replace("\r", "")),
//This one should be LIMITED to only 5 threads MAX!
grab2 = checktwo(Hi, Hello)
}))
在上面的代碼中我添加了grab2
,它應該分配最多5個線程。
說實話,我不知道如何執行這樣的方法。 任何幫助,將不勝感激。
如果你需要一些代碼只由n
線程執行,你需要一個信號量 ,在這種情況下SemaphoreSlim
就足夠了
// 5 threads to run in parallel, all 5 can start immidiately
var semaphore = new SemaphoreSlim(5, 5);
// ...
try
{
semaphore.Wait();
//This one should be LIMITED to only 5 threads MAX!
grab2 = checktwo(Hi, Hello);
}
finally
{
// ensure the release of semaphore
semaphore.Release();
}
您甚至可以在async
方法中等待它:
await semaphore.WaitAsync();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.