2
我有这种功能。C中的闭包lambda表达式#
function SomeFunction()
{
const int NUMBER_OF_CONCURENT_THREADS = 50;
List<Guid> sessions = new List<Guid>();
ManualResetEvent[] doneEvents = new ManualResetEvent[NUMBER_OF_CONCURENT_THREADS];
Action<int> makeServiceCall = (iter) =>
{
var proxy = GetProxy();
sessions.Add(proxy.GetCurrentSessionId());
doneEvents[iter].Set();
};
for (int i = 0; i < NUMBER_OF_CONCURENT_THREADS; ++i)
{
doneEvents[i] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem((o) =>
{
int iter = i;
makeServiceCall(iter);
});
}
WaitHandle.WaitAll(doneEvents);
Assert.AreEqual(50, sessions.Count);
}
的问题是,我得到IndexOutOfRangeException
在doneEvents[iter].Set();
行代码时。请任何想法如何解决它?
Eric Lippert写了一篇关于关闭循环变量的文章。看看http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx – Alex 2012-02-28 09:31:18