【问题标题】:(benchmark) endless loop without freezing the thread(基准)无限循环而不冻结线程
【发布时间】: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;
    }
}

}

【问题讨论】:

标签: c# infinite-loop


【解决方案1】:

您现在在 UI 线程上运行所有内容,因此 BackgroundWorker 选项还不错。

您确实必须深入研究多线程编程,尽管以下内容可以提供一个良好的开端: http://codesamplez.com/programming/multithreaded-programming-c-sharp

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 1970-01-01
    • 2020-04-21
    • 2014-11-12
    相关资源
    最近更新 更多