这让我很难理解这种情况下的实际行为。当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();
}
}
使用它有谁请洗完澡一些关于它的光?提前致谢。
非常感谢解释执行的顺序。这是我的不好:(我没有注意到使用“使用”和“任务”的错误。再次感谢。 –