简体   繁体   中英

Tasks in C# are executing sequentially and not concurrently

For purely experimental reasons, I am trying to write a psuedo-random number generator using Task s 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.

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.

Can I ask why you're not just generating "bits" using this:

Random r = new Random();
r.Next(2);

or better yet:

Random r = new Random();
byte[] randomBytes = new byte[7];
r.NextBytes(randomBytes);

In any case, assuming you have a weird requirement to do what you're doing, are you sure they're running sequentially?

I would say it's more likely that the first Task is ending before the second Task has a chance to start.

In any case, this would be the same thing, but you could try:

Task.WaitAll(
    new Task( () => this.display(1) ),
    new Task( () => this.display(0) )
);

If you're desperate to use what you have, you could do a Random generation to decide which Task starts first:

Random r = new Random();

Task task = new Task(() => this.display(1));
Task task2 = new Task(() => this.display(0));
Task[] tasks = new [] { task, task2 };

/* Only supports 2 tasks */
int firstTask = r.Next(2); 

tasks[firstTask].Start();
tasks[firstTask ^ 1].Start();

Task.WaitAll();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM