Search code examples
c#.netmultithreadingtask-parallel-librarystatic-variables

Tasks in C# are executing sequentially and not concurrently


For purely experimental reasons, I am trying to write a psuedo-random number generator using Tasks in C#

I have 2 tasks, and 2 static variables glo_a and glo_count. glo_a is supposed to hold the final result (a 7-bit random binary integer).

public static int glo_a = 0, glo_count = 6;

Private void button1_Click(object sender, RoutedEventArgs e)
{
  Task task = new Task(() => this.display(1));
  Task task2 = new Task(() => this.display(0));

  task.Start();
  task2.Start();

  Task.WaitAll();
  textBox1.AppendText("\n" + glo_a);
}

public void display(int j)
{
  for (; glo_count >= 0; glo_count--)
  {  
    glo_a += j * (int)Math.Pow(10,glo_count);
  }
}

private void refreshbutton_Click(object sender, RoutedEventArgs e)
{
  /* reset the original values*/  
  glo_a = 0;
  glo_count = 6;
  textBox1.Text = "";  
}

The problem I'm having is that task executes first and completes before task2 begins every single time.


Solution

  • As the tasks have very little to do chances are they'll end up running one after the other, and since you started task1 first, that's likely to get run first.

    As other answers have said, just use the Random class.