Solved

C# - Time Condition

Posted on 2012-03-14
10
215 Views
Last Modified: 2012-03-15
Hello everybody.
My Desktop: Windows 7 Ultimate 64 bis, Visual Studio 2010 Ultimate.
 
I'm trying to implement this routine in C# WinForm.
A condition must work within 10 minutes.
If time runs out and the condition is not satisfied, the routine stops and displays a message that has not reached the condition.

Now, within these 10 minutes the condition is satisfied, stop the clock and display a message that the condition was satisfied.

if (x >= 100)
{
       //stop the timer	
       label1.Text = "x >= 100";
}

if (timerx == 10 minutes)
{
       label1.Text = "Time over x < or != 100";

}

Open in new window


Thank you,
ocaccy
0
Comment
Question by:ocaccy
  • 4
  • 4
  • 2
10 Comments
 
LVL 20

Assisted Solution

by:BuggyCoder
BuggyCoder earned 167 total points
ID: 37719974
class program {
private static int value = 0;

static void Main(string[] args)
        {
            try
            {
                ThreadPool.QueueUserWorkItem(o => StartChecking());
                Thread.sleep(10000);
                value=1;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }

public static void StartChecking()
        {
            var startTime = DateTime.Now;

            while(true)
            {
                if (startTime.AddMinutes(1) < DateTime.Now)
                {
                    Console.WriteLine("Time Exceeded");
                    break;
                }

                //Our Condition
                if (value > 0)
                {
                    Console.WriteLine("Condition Met!!!");
                    break;
                }

                //Lets sleep for 1 sec.
                Thread.Sleep(1000);
            }
        }

Open in new window


Above code tell you basically how to achieve this.
In winforms, however you can use BackgroundWorker for achieving Asynchronous functionality. Here is link to help you with that:-
http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx
0
 
LVL 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 333 total points
ID: 37720083
We need more details.  How is "x" being computed?  You may need another thread to do that work on.  As BuggyCoder suggests, a BackgroundWorker() control could work.  If "x" is being computed on another thread then you can use a simple Timer on the Form to determine when 10 minutes has passed.  The timing could also be accomplished in the worker thread but we'd need to see code for that.
0
 

Author Comment

by:ocaccy
ID: 37720358
if we use

 ThreadPool.QueueUserWorkItem(o => StartChecking());
                Thread.sleep(10000);
               
will not stop processing?

If this "Thread.sleep" stop the processing, we can not use this.
 
My data is coming from the USB connection which has 6 devices interspersed by RS485/USB converter.

Every 10 seconds, send command and receive data from devices.

It turns out that to wait until all devices have a difference of  less than ±10%.

But if the data do not reach  less than ±10% in those 10 minutes, we should display a message.

If within these 10 minutes to reach less than ±10%, then we can stop the clock and show the success message.

Thank you,
ocaccy
0
 
LVL 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 333 total points
ID: 37720473
Alright...so you probably already have the communication with the devices all squared away.  I assume that is working without blocking the UI?

Do you need an actual "countdown" on your screen?...or just a way to stop the process after 10 minutes?
0
 

Author Comment

by:ocaccy
ID: 37720707
Yes, the communication with devices probably is ok, I think so
I need the Both!

Thank you,
ocaccy
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 333 total points
ID: 37720891
Here's a simple countdown timer:
Public Class Form1

    Private TargetDateTime As DateTime

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Timer1.Interval = 1000
        Timer1.Enabled = False
    End Sub

    Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        Button1.Enabled = False
        TargetDateTime = DateTime.Now.AddMinutes(10)
        UpdateTimer()
        Timer1.Start()
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
        UpdateTimer()
    End Sub

    Private Sub UpdateTimer()
        Dim ts As TimeSpan = TargetDateTime.Subtract(DateTime.Now)
        If ts.TotalMilliseconds > 0 Then
            Label1.Text = "-" & ts.Minutes & ":" & ts.Seconds.ToString("00")
        Else
            Label1.Text = "Time's Up!"
            Timer1.Stop()
            MessageBox.Show("Done!")
            Button1.Enabled = True
        End If
    End Sub

End Class

Open in new window


If your "x" value reaches your target point then simply turn off Timer1.
0
 
LVL 20

Assisted Solution

by:BuggyCoder
BuggyCoder earned 167 total points
ID: 37721553
my idea of adding sleep in main method was to change the condition after just waiting for 10 secs. Just to let you know the method will exit even after the condition meet.

the routine that is executing the timer is running in StartChecking method.
You can process response from each usb in the startchecking method by just replacing the conditional if block with your condition..
0
 

Author Comment

by:ocaccy
ID: 37723722
Hi BuggyCoder,

I'll test your code.
If really does not sleep the access the USB port, I think is a good idea.
Idle_Mind, forgive me please.
I'm using C #, and do not have much familiarity with VB.

Thank you,
ocaccy
0
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 333 total points
ID: 37724519
Ha!...sorry.  I use them both and am always forgetting what zone I'm in.

Here's a C# version:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private DateTime TargetDateTime;

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Interval = 1000;
            timer1.Enabled = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            TargetDateTime = DateTime.Now.AddMinutes(10);
            UpdateTimer();
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            UpdateTimer();
        }

        private void UpdateTimer()
        {
            TimeSpan ts = TargetDateTime.Subtract(DateTime.Now);
            if (ts.TotalMilliseconds > 0)
            {
                label1.Text = "-" + ts.Minutes.ToString() + ":" + ts.Seconds.ToString("00");
            }
            else
            {
                label1.Text = "Time's Up!";
                timer1.Stop();
                MessageBox.Show("Done!");
                button1.Enabled = true;
            }
        }

    }
}

Open in new window

0
 

Author Closing Comment

by:ocaccy
ID: 37727922
Thank you.
Solve two problems.

Regards,
ocaccy
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.
Hi friends,  in this video  I'll show you how new windows 10 user can learn the using of windows 10. Thank you.

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now