tags:

views:

31

answers:

1

Hi there, trying to grasp the TPL.

Just for fun I tried to create some Tasks with a random sleep to see how it was processed. I was targeting a fire and forget pattern..

static void Main(string[] args)
    {
        Console.WriteLine("Demonstrating a successful transaction");

        Random d = new Random();
        for (int i = 0; i < 10; i++)
        {
            var sleep = d.Next(100, 2000);


            Action<int> succes = (int x) =>
            {
                Thread.Sleep(x);
                Console.WriteLine("sleep={2}, Task={0}, Thread={1}: Begin successful transaction",
                   Task.CurrentId, Thread.CurrentThread.ManagedThreadId, x);
            };

            Task t1 = Task.Factory.StartNew(() => succes(sleep));
        }
        Console.ReadLine();
    }

But I don't understand why it outputs all lines to the Console ignoring the Sleep(random)

Can someone explain that to me?

+2  A: 

Your code uses the value of i instead of the generated random number. It does not ignore the sleep but rather sleeps between 0 and 10ms each iteration.

Try:

Thread.Sleep(sleep);
MarvinLabs
Just a typo, edited the original code. The question remains the same!
Janus007