简体   繁体   中英

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;}
     }


}

In this example I'm running function RunIt in a loop. RunIt starts a process asynchronously and assign anonymous handler when it's done. In the same function we have a context variable which will be captured by anonymous lambda. My question is simple - can I assume that captured context will always match the result? My concern here is that I'm running it 10 times which means successHandler will be called 10 times in unordered manner. Is there a separate version of anonymous function per each context?

Long story short - will context.Id always match successHandler "id" in anonymous function?

I know this question was downvoted but I'll answer it anyway. The answer is yes, Context variable will be captured separately per each iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM