簡體   English   中英

在循環中關閉和捕獲局部變量

[英]Closure and capturing local variable in a loop

using System;

public class Program
{
    public static void Main()
    {
        IRunnable runnable = new Runnable();
        for(int i=0;i<10;i++)
        {
            RunIt(runnable);
        }

    }

    public static void RunIt(IRunnable runnable)
    {
        var context = new Context();
        context.Id = runnable.RunAsync((id,result)=>{
            //context.Id will always match "id" here?
            context.Result = result; // can I assume here that this is the same context?
        });
    }


    public interface IRunnable
    {
        int RunAsync(Action<string,string> successHandler);
    }

    public class Runnable : IRunnable
    {
       private Random _random = new Random();

        public string RunAsync(Action<string,string> successHandler)
        {

            var guid = Guid.NewGuid().ToString();
            Task.Run(()=>
             {
               Thread.Sleep(_random.Next(0,1000));
                successHandler(guid, "result")
             });
            return guid;
        }
    }

      public class Context
    {
        public string Id {get;set;}
        public string Result{get;set;}
     }


}

在這個例子中,我在循環中運行函數RunIt RunIt異步啟動一個進程,並在完成后分配匿名處理程序。 在同一個函數中,我們有一個上下文變量,它將被匿名 lambda 捕獲。 我的問題很簡單 - 我可以假設捕獲的上下文將始終與結果匹配嗎? 我在這里擔心的是我運行了 10 次,這意味着 successHandler 將以無序方式調用 10 次。 每個上下文是否有單獨的匿名函數版本?

長話短說 - context.Id總是匹配匿名函數中的 successHandler“id”?

我知道這個問題被否決了,但無論如何我都會回答。 答案是肯定的,每次迭代都會單獨捕獲Context變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM