0

I am really not sure if I am misunderstanding something here and I am generally not sure what to look for to possibly find a solution, which is why I am asking it here.

First of all, here is my code:

class Program
{
    static void Main(string[] args)
    {
        int sleepTime = 10000;
        const int totalTasksToCreate = 10;
        Task[] tasks = new Task[totalTasksToCreate];
        for (int i = 0; i < totalTasksToCreate; ++i)
        {
            tasks[i] = Task.Factory.StartNew(() => TaskAction(sleepTime));
            sleepTime /= 2;
        }

        Task.WaitAll(tasks);
    }

    private static void TaskAction(int sleepTime)
    {
        Thread.Sleep(sleepTime);
        Console.WriteLine(sleepTime);
        Console.Beep();
    }
}

It is pretty basic, I just somehow wanted to create A Beeping-Machine that beeps in shorter intervals after each beep (And I wanted to do it with tasks because of reasons).

However, I kept wondering why the Sleep-Time was always almost 0 (or 9 in this case) and I really am unsure as to why this is as I am only halving the Value after creating the Task with the Task-Factory.

Is the int-Parameter passed by Reference? Or has it something to do with the StartNew-Method being async?

I am sorry but I am new working with Tasks and Multi-Threading and I cant seem to find any existing questions to this topic or even any discussions elsewhere where there is the same question.

Thanks in advance

BotMaster3000
  • 472
  • 4
  • 16
  • You're passing the tasks lambdas that all use the same shared variable. You start at 10000 and halve the value ten times before the first task ever gets a chance to use the value. Or something. – 15ee8f99-57ff-4f92-890c-b56153 Jun 25 '19 at 17:45
  • 3
    tasks don't start immediately, and `sleepTime` is not evaluated in a task until it starts, so by the time they all start, the loop has completed and the value of `sleepTime` is the same for all of them. To fix this, make a copy of `sleepTime` inside the loop so it's local to that iteration, and use that for the task. – Rufus L Jun 25 '19 at 17:47
  • Uff, I would've thought that the Value of the variable gets passed right away and not some possible time in the future.. But that fixed it for me and I can consider it in the future now, thanks alot – BotMaster3000 Jun 25 '19 at 17:52
  • I advise you to use `await Task.Delay` instead of `Thread.Sleep`, you shouldn't "block" a thread in your case, but rather a task – Darjan Bogdan Jun 25 '19 at 18:01
  • @BotMaster3000 You're passing a lambda. Imagine what that would mean: You're expecting the runtime -- not the compiler -- to go through the code in the lambda and convert all the variables to constants at some arbitrary moment. – 15ee8f99-57ff-4f92-890c-b56153 Jun 25 '19 at 18:06

0 Answers0