数据记录器在启动时停止响应 [英] Data logger stopped responding when started

查看:102
本文介绍了数据记录器在启动时停止响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。我创建了一个数据记录器,一旦表单加载,它会检查.ini文件是否有要测试的单元的序列号。它每5秒检查一次.ini文件,并在列表框中显示该字符串。另一方面,我有一个按钮'start'来启动日志记录过程,我还没有完成日志记录过程,但我现在在button_click方法中所拥有的是它将运行的时间取决于运算符,例如8小时。我用了

Hi. I've created a data logger that once the form is loaded, it checks for an .ini file if it has the serial number of the unit to be tested. It checks the .ini file every 5 seconds and display the string in a listbox. On the other hand, I have a button 'start' to start the logging process, I havent finished the logging process, but what I have right now in that button_click method is the time it will run depends on the operator for example 8 hrs. I used

DateTime start = DateTime.Now
DateTime stop = start.AddHours(8)
while (stop > start)
{
 //Log data
}





每当我点击按钮,记录器只是冻结,没有响应。我认为这些方法是罪魁祸首。关于如何正确实现这些方法的任何建议?



whenever I click the button, logger just freeze, not responding. I'm thinking that these methods are the culprits. Any suggestions on how I can implement these methods properly?

推荐答案

private Thread _loggerThread;
private readonly object _lockLoggerThread = new object();

private void StartLogging()
{
    StopLogging();

    var thread = new Thread(() =>
    {
        try
        {
            var end = DateTime.Now.AddHours(8);
            while (DateTime.Now < end)
            {
                // Log what you want

                Thread.Sleep(5000); // wait 5 seconds
            }
        }
        catch (ThreadInterruptedException)
        {
        }
    });

    lock (_lockLoggerThread)
    {
        _loggerThread = thread;
        _loggerThread.Start();
    }
}

private void StopLogging()
{
    lock (_lockLoggerThread)
    {
        if (_loggerThread != null && _loggerThread.IsAlive)
        {
            _loggerThread.Interrupt();
        }
        _loggerThread = null;
    }
}


这篇关于数据记录器在启动时停止响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆