Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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
C#
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?
Posted
Updated 27-Aug-15 22:33pm
v2
Comments
Herman<T>.Instance 28-Aug-15 4:32am    
as long while (stop > start) = true it stays in the while. So your screen freezes because you want him to do the while because it is true
Do you understand the concept of while?

Each 5 seconds? sounds like a TIMER solution
letsirhc 28-Aug-15 4:47am    
@digimanus so what could be a better approach if I want to run a method (logging process) in a certain time(ex.8) while there is a method running every 5 seconds? I understand that while loop will not be finished until the condition is false

1 solution

C#
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;
    }
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900