繁体   English   中英

(基准)无限循环,不冻结线程

[英](benchmark) endless loop without freezing the thread

我正在编写一个散列哈希的小型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;
    }
}

}

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

尽管以下内容可能会带给您领先的优势,但您确实必须投入多线程编程的工作: http : //codesamplez.com/programming/multithreaded-programming-c-sharp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM