-2

Fire and forget method in C#

I refered different issues for 'Fire and Forget in C#'

i.e. Simplest way to do a fire and forget method in C#? . . and few several,

but i have an another issue with the same.i wrote following code

static void Main(string[] args)
    {
        for (int i = 0; i < 5; i++)
        {
            //fireAway(i);
            Task.Factory.StartNew(() => fireAway(i));
        }
        Console.WriteLine("Main Finished");
        Console.Read();
    }

public static void fireAway(int i)
    {
        System.Threading.Thread.Sleep(5000);
        Console.WriteLine("FireAway" + i);
    }

where i am expecting output like

Main Finished

FireAway0

FireAway1

FireAway2

FireAway3

FireAway4

but output is

Main Finished

FireAway5

FireAway5

FireAway5

FireAway5

FireAway5

very honestly i am new to threading concept, i need help. How can i meet with expected output..?

Community
  • 1
  • 1
umesh_vn
  • 85
  • 4

2 Answers2

1

The threads are started after the loop is finished. When the loop is finished the value of i is 5. You have to capture the value of i before you send it to StartNew(..)

for (int i = 0; i < 5; i++)
{
      int tmp = i;
      Task.Factory.StartNew(() => fireAway(tmp));
}
Vadim Martynov
  • 8,602
  • 5
  • 31
  • 43
mortb
  • 9,361
  • 3
  • 26
  • 44
-1

You should pass parameter to your method, not use i, because the method will start to execute only after you finish to iterate, see here

Buda Gavril
  • 21,409
  • 40
  • 127
  • 196