我想用winform尝试做一个雪花一样的特效,运行起来效果是对的,可是运行了一会之后,有时候几十分钟,有时候几个小时,突然就炸了,Program.cs报错,附代码,如图
public partial class Form1 : Form
{
int max = 20;
double[] snowArray;
Label[] labelArray;
int newSnowNum = 0;
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
snowArray = new double[max];
labelArray = new Label[max];
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
CenterToScreen();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void move(int arrayNum)
{
if (labelArray[arrayNum] == null)
{
GetNewLabel(arrayNum);
}
int left = labelArray[arrayNum].Location.X;
if (left <= 5 || left > 1000)
{
labelArray[arrayNum].Dispose();
labelArray[arrayNum] = null;
return;
}
int ran = new Random().Next(0, 2);
if (ran == 1)
{
if (snowArray[arrayNum] < 6)
{
snowArray[arrayNum] += 0.4;
}
}
else
{
if (snowArray[arrayNum] > -6)
{
snowArray[arrayNum] -= 0.4;
}
}
labelArray[arrayNum].Location = new Point(labelArray[arrayNum].Location.X + (int)(snowArray[arrayNum] + 0.5 * (snowArray[arrayNum] > 0 ? 1 : -1)), (labelArray[arrayNum].Location.Y + (new Random().Next(0, 2) == 1 ? 2 : 1)));
if (labelArray[arrayNum].Location.X > 1000 || labelArray[arrayNum].Location.X < 0 || labelArray[arrayNum].Location.Y > 500)
{
labelArray[arrayNum].Dispose();
labelArray[arrayNum] = null;
return;
}
SetTimeout(1000 / 24, arrayNum);
//move(arrayNum);
}
private void GetNewLabel(int arrayNum)
{
Label lb = new Label();
lb.Text = "hehe";
lb.Name = Guid.NewGuid().ToString();
lb.Size = new Size(29, 12);
Random ran = new Random();
int firstPositionLeft = ran.Next(0, 1000);
lb.Location = new Point(firstPositionLeft, 0);
labelArray[arrayNum] = lb;
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(delegate { AddLabel(lb); }));
return;
}
this.Controls.Add(lb);
}
private void Form1_Shown(object sender, EventArgs e)
{
move(0);
SetInterval(1000);
}
private void AddLabel(Label lb)
{
this.Controls.Add(lb);
}
/// <summary>
/// 在指定时间过后执行指定的表达式
/// </summary>
/// <param name="interval">事件之间经过的时间(以毫秒为单位)</param>
/// <param name="action">要执行的表达式</param>
private void SetTimeout(double interval, int num)
{
System.Timers.Timer timer = new System.Timers.Timer(interval);
timer.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e)
{
timer.Enabled = false;
move(num);
};
timer.Enabled = true;
}
/// <summary>
/// 在指定时间周期重复执行指定的表达式
/// </summary>
/// <param name="interval">事件之间经过的时间(以毫秒为单位)</param>
/// <param name="action">要执行的表达式</param>
private void SetInterval(double interval)
{
System.Timers.Timer timer = new System.Timers.Timer(interval);
timer.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e)
{
if (newSnowNum < max - 1)
{
move(++newSnowNum);
}
else
{
newSnowNum = 0;
move(0);
}
};
timer.Enabled = true;
}
}