代码之家  ›  专栏  ›  技术社区  ›  Howard Hoffman

使用匿名委托。NET线程池。排队用户工作项

  •  6
  • Howard Hoffman  · 技术社区  · 17 年前

    List< Thing > things = MyDb.GetTheThings();
    foreach( Thing t in Things)
    {
        localLogger.DebugFormat( "About to queue thing [{0}].", t.Id );
        ThreadPool.QueueUserWorkItem(
            delegate()
            {
                try
                {
                    WorkWithOneThing( t );
                }
                finally
                {
                    Cleanup();
                    localLogger.DebugFormat("Thing [{0}] has been queued and run by the delegate.", t.Id ); 
                }
            });
     }
    

    霍华德·霍夫曼

    3 回复  |  直到 17 年前
        1
  •  7
  •   Community Mohan Dere    9 年前

    This question 详细讨论了这一语言特征及其含义。

        2
  •  1
  •   Jeff Yates    17 年前

    这在使用闭包时很常见,在构造LINQ查询时尤其明显。闭包引用变量,而不是它的内容,因此,为了使您的示例正常工作,您可以在循环中指定一个取值为t的变量,然后在闭包中引用它。这将确保匿名委托的每个版本引用不同的变量。

        3
  •  1
  •   Quintin Robinson    17 年前

    下面是一个详细说明为什么会发生这种情况的链接。它是为VB编写的,但C#具有相同的语义。

    http://blogs.msdn.com/jaredpar/archive/2007/07/26/closures-in-vb-part-5-looping.aspx