【发布时间】:2014-09-22 21:43:23
【问题描述】:
我正在编写一个散列散列的小型 c# 程序。我希望它做两件事(有点像基准测试):
hash = md5.ComputeHash(hash);
tell me how many times per second it can do this.
目前,我有一个带有 OnTimedEvent 的计时器来跟踪每秒通过多少散列,以及一个无限的 while(true) 循环来保持散列的进行。一旦散列开始,我的程序和计时器就会停止。
这样做的正确方法是什么?如何在不冻结的情况下继续散列(并输出)?
提前致谢!
马丁
此时,除了计时器之外,一切都是线性的。
public partial class Form1 : Form
{
private int count;
private MD5 md5;
private byte[] hash;
private bool Calculate = false;
private System.Timers.Timer timer;
public Form1()
{
InitializeComponent();
count = 0;
PrepareFirstHash();
timer = new System.Timers.Timer(1000);
timer.Elapsed += OnTimedEvent;
timer.Enabled = true;
}
private void PrepareFirstHash()
{
md5 = MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes("start");
hash = md5.ComputeHash(inputBytes);
}
private void DoCalc()
{
hash = md5.ComputeHash(hash);
count++;
}
private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
SetText(count.ToString());
count = 0;
}
delegate void SetTextCallback(string text);
private void SetText(string text)
{
if (this.label1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.label1.Text = text;
}
}
private void btnStart_Click(object sender, EventArgs e)
{
Calculate = true;
while (Calculate){
DoCalc();
}
}
private void btnStop_Click(object sender, EventArgs e)
{
Calculate = false;
}
}
}
【问题讨论】:
-
听起来像是
BackgroundWorker的工作。见msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx -
如果您只是计时单一方法,为什么不使用控制台应用程序和
System.Diagnostics.Stopwatch?
标签: c# infinite-loop