我对 C# 相当陌生,我制作了一个模拟乐透抽奖的简单程序。它采用第一个(随机)数字并计算赢得多少平局。这是波兰乐透,所以有 6 个号码可以匹配。
当程序以简单的 for 循环运行时,一切正常。但是有一个问题,当我使用 Parallel For 或任何其他多任务或多线程选项时。
首先是代码:
class Program
{
public static int howMany = 100;
static void Main(string[] args)
{
Six my;
Six computers;
long sum = 0;
double avg = 0;
int min = 1000000000;
int max = 0;
for (int i = 0; i < howMany; i++)
{
my = new Six();
Console.WriteLine((i + 1).ToString() + " My: " + my.ToString());
int counter = 0;
do
{
computers = new Six();
counter++;
} while (!my.Equals(computers));
Console.WriteLine((i + 1).ToString() + " Computers: " + computers.ToString());
Console.WriteLine(counter.ToString("After: ### ### ###") + "\n");
if (counter < min)
min = counter;
if (counter > max)
max = counter;
sum += counter;
}
avg = sum / howMany;
Console.WriteLine("Average: " + avg);
Console.WriteLine("Sum: " + sum);
Console.WriteLine("Min: " + min);
Console.WriteLine("Max: " + max);
Console.Read();
}
}
class Six : IEquatable<Six>
{
internal byte first;
internal byte second;
internal byte third;
internal byte fourth;
internal byte fifth;
internal byte sixth;
private static Random r = new Random();
public Six()
{
GenerateRandomNumbers();
}
public bool Equals(Six other)
{
if (this.first == other.first
&& this.second == other.second
&& this.third == other.third
&& this.fourth == other.fourth
&& this.fifth == other.fifth
&& this.sixth == other.sixth)
return true;
else
return false;
}
private void GenerateRandomNumbers()
{
byte[] numbers = new byte[6];
byte k = 0;
for (int i = 0; i < 6; i++)
{
do
{
k = (byte)(r.Next(49) + 1);
}while (numbers.Contains(k));
numbers[i] = k;
k = 0;
}
Array.Sort(numbers);
this.first = numbers[0];
this.second = numbers[1];
this.third = numbers[2];
this.fourth = numbers[3];
this.fifth = numbers[4];
this.sixth = numbers[5];
}
public override string ToString()
{
return this.first + ", " + this.second + ", " + this.third + ", " + this.fourth + ", " + this.fifth + ", " + this.sixth;
}
}
当我尝试使其成为 Parallel.For 时:
long sum = 0;
double avg = 0;
int min = 1000000000;
int max = 0;
Parallel.For(0, howMany, (i) =>
{
Six my = new Six();
Six computers;
Console.WriteLine((i + 1).ToString() + " My: " + my.ToString());
int counter = 0;
do
{
computers = new Six();
// Checking when it's getting stuck
if (counter % 100 == 0)
Console.WriteLine(counter);
counter++;
} while (!my.Equals(computers));
Console.WriteLine((i + 1).ToString() + " Computers: " + computers.ToString());
Console.WriteLine(counter.ToString("After: ### ### ###") + "\n");
// It never get to this point, so there is no problem with "global" veriables
if (counter < min)
min = counter;
if (counter > max)
max = counter;
sum += counter;
});
程序在某个时候卡住了。计数器达到〜3,000-40,000并且拒绝走得更远。
我尝试了什么:
- 使类成为结构
- 每约 1000 次迭代收集垃圾
- 使用线程池
- 使用任务运行
- 仅制作随机类程序成员(厌倦了使六类“更轻”)
但我一无所获。
我知道这对你们中的一些人来说可能是一件非常简单的事情,但是人们必须以某种方式学习;)我什至买了一本关于异步编程的书,以找出它为什么不起作用,但无法弄清楚。