这让我很难理解这种情况下的实际行为.实际上在没有执行任务时会发生什么事情,但是稍后当SemaphoreSlim被处置时.它引发了我的异常 –
System.ObjectDisposedException {“信号量已被释放.”}
System.ObjectDisposedException {“信号量已被释放.”}
我有一个类库 –
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(); } }
有人可以请点亮一下吗?提前致谢.