我正在尝试使用UWP可视化表示随机数的生成。画布上基本上有X个矩形,每个矩形代表一个数字,因此第一个矩形为0,第二个矩形为1,依此类推。代表此矩形的类具有以下属性:
public class Representer
{
public int TimesChosen { get; set; }
public int NumberRepresented { get; set; }
public double CurrentProportion { get; set; }
public double RectangleWidth { get; set; }
public Rectangle Rect { get; set; }
.
.
}
每次生成数字时,对应的代表都会获得变量“ TimesChosen”加1。此访问是通过Manager类中的字典进行的:
public class Manager
{
public Canvas CanvasManaged { get; set; }
public double NumbersGenerated { get; set; }
public readonly int Range;
public Dictionary<int, Representer> Representers = new Dictionary<int, Representer>();
.
.
}
生成数字时,必须将这些矩形的高度更新为它们相应的比例,例如,如果我有5个矩形,并且所有它们的编号生成的时间相等,则所有矩形的比例为20%,因此它们的高度必须是画布的20%。我尝试更新所有矩形比例及其高度的方法是通过一个事件。每次生成数字时,管理器都会引发一个事件,告知所有矩形必须更新:
public async void GenerateNumber(TextBlock Iterations)
{
Random Random = new Random();
while (true)
{
int Number = Random.Next(this.Range);
this.NumbersGenerated += 1;
Representers[Number].TimesChosen += 1;
await Task.Run(() =>
{
OnNumberGenerated();
});
Iterations.Text = this.NumbersGenerated.ToString();
}
}
public virtual void OnNumberGenerated()
{
NumberGenerated?.Invoke(this, new ManagerArgs { NumbersGenerated = this.NumbersGenerated, CanvasManaged = this.CanvasManaged });
}
代表中OnNumberGenerated的实现是:
public async void OnNumberGenerated(object source, ManagerArgs e)
{
this.CurrentProportion = this.TimesChosen / e.NumbersGenerated;
await Task.Run(async () =>
{
await e.CanvasManaged.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
this.Rect.Height = e.CanvasManaged.Height * this.CurrentProportion;
this.Rect.Fill = new SolidColorBrush(Color.FromArgb(255, Convert.ToByte(255 * this.CurrentProportion), Convert.ToByte(255 * (1 - this.CurrentProportion)), 0));
});
});
}
问题在于性能确实很差,例如,如果我有1000个矩形,则更新速度约为10个矩形/秒。我想到:事件引发后,以什么方式调用OnNumberGenerated的实现?有没有办法使这些实现被异步或在线程中调用?有什么办法可以改善程序的性能?