這讓我很難理解這種情況下的實際行爲。當SemaphoreSlim被處置時,實際上發生的是不執行任務。它拋出我下面exception- System.ObjectDisposedException {"The semaphore has been disposed."}
代碼有什麼問題
我有一個類庫一樣 -
public class ParallelProcessor
{
private Action[] actions;
private int maxConcurrency;
public ParallelProcessor(Action[] actionList, int maxConcurrency)
{
this.actions = actionList;
this.maxConcurrency = maxConcurrency;
}
public void RunAllActions()
{
if (Utility.IsNullOrEmpty<Action>(actions))
throw new Exception("No Action Found!");
using (SemaphoreSlim concurrencySemaphore = new SemaphoreSlim(maxConcurrency))
{
foreach (Action action in actions)
{
Task.Factory.StartNew(() =>
{
concurrencySemaphore.Wait();
try
{
action();
}
finally
{
concurrencySemaphore.Release();
}
});
}
}
}
}
而且喜歡 -
class Program
{
static void Main(string[] args)
{
int maxConcurrency = 3;
Action[] actions = new Action[] {() => Console.WriteLine(1),() => Console.WriteLine(2),() => Console.WriteLine(3) }; //Array.Empty<Action>();
ParallelProcessor processor = new ParallelProcessor(actions, maxConcurrency);
processor.RunAllActions();
Console.ReadLine();
}
}
使用它有誰請洗完澡一些關於它的光?提前致謝。
非常感謝解釋執行的順序。這是我的不好:(我沒有注意到使用「使用」和「任務」的錯誤。再次感謝。 –