-1

出于纯粹的实验原因,我正在尝试Task在 C# 中使用 s编写一个伪随机数生成器

我有 2 个任务,2 个静态变量glo_aglo_count. glo_a应该保存最终结果(一个 7 位随机二进制整数)。

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 = "";  
}

我遇到的问题是每次都task先执行并在开始之前完成。task2

4

2 回答 2

3

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.

于 2011-05-06T06:58:50.993 回答
2

我可以问你为什么不只是使用这个来生成“位”:

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

或者更好:

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

无论如何,假设你有一个奇怪的要求来做你正在做的事情,你确定它们是按顺序运行的吗?

我想说第一个任务更有可能在第二个任务有机会开始之前结束。

无论如何,这将是同一件事,但您可以尝试:

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

如果您不顾一切地使用您所拥有的,您可以进行随机生成来决定哪个任务首先开始:

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();
于 2011-05-06T06:53:27.693 回答