2014-09-22 37 views
0

我正在写一个小的C#程序哈希哈希。我想它做的两件事情(有点像基准):(基准)无止境的循环没有冻结线程

hash = md5.ComputeHash(hash); 
tell me how many times per second it can do this. 

目前,我有一个计时器与OnTimedEvent跟踪多少哈希通过每秒来无限,而(真)环保持哈希。一旦哈希开始,我的程序和定时器就会被冻结。

这样做的正确方法是什么?我怎样才能保持散列(并输出)而不会冻结?

提前致谢!

马腾

此时一切除计时器Quiete酒店线性。

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

}

+0

听起来像是'BackgroundWorker'工作。请参阅http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx – Vlad 2014-09-22 21:59:17

+0

如果您只是计时一种方法,为什么不使用控制台应用程序和'System.Diagnostics。 Stopwatch'? – 2014-09-22 22:04:06

回答