-1

Program.cs:

class Program
{
    static void Main()
    {
        Class1 c1 = new Class1();
        for(int i=0;i<2;i++)
        {
            Thread t = new Thread(() =>
              {
                  c1.pr(i);
              });
            t.Start();
        }
    }

}

Class1.cs:

public class Class1
    {
        public void pr(int i)
        {
           Console.WriteLine((i).ToString());
        }
    }

Result: 2 2

I want the result to be 0 1. For each thread, value of i is assigned to function 'pr'.

If i add t.Join() after t.Start() it works. But the joined thread has to wait until other threads have done their works, is there any solution that provide the same result without using Join() function? I want to execute them at a same time

  • Try to set temporary variable inside loop `var temp = i; Task.Run(() => c1.pr(temp));` – Fabio Aug 31 '21 at 08:41
  • [Using the iteration variable in a lambda expression may have unexpected results](https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/error-messages/using-the-iteration-variable-in-a-lambda-expression-may-have-unexpected-results) – Fabio Aug 31 '21 at 08:44

1 Answers1

0

What you are currently (perhaps unknowingly) doing is creating a thread for each iteration, this makes little sense. You should do something like this:

Put the for-loop inside of the lambda function.

    Thread t = new Thread(() =>
    {
        for(int i=0;i<2;i++)
        {
            c1.pr(i);
        }
    });
    t.Start();

Then you can create as many threads as you need and they will all print their own iterations of the loop variable.

Small tangent: Interestingly the reason why a '2' is printed twice in your example is not intuitive and is a known "issue" with lambda functions, as they only capture the value of the closure. Take a look at this question, if you are interested in the topic.

AsPas
  • 359
  • 5
  • 22
  • No problem. And don't get discouraged if people downvote your question. People here at StackOverflow try to help but expect stuff in a very specific format. Because this helps us help you. Good luck! – AsPas Aug 31 '21 at 09:41
  • I'm interested in knowing what meaning you're trying to convey with the double quotes around "issue"? – Enigmativity Aug 31 '21 at 23:09
  • @Enigmativity well, AFAIK it's not really an issue per se, rather, from what I understand it's the consequence of capturing the value of a variable while it's being iterated. I'm trying to convey that this is not a bug and it will not be fixed, but it can present a problem for those who are unaware. – AsPas Sep 01 '21 at 08:41
  • Good explanation. I like it. – Enigmativity Sep 01 '21 at 23:42