Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

C# - Time Condition

Posted on 2012-03-14
10
Medium Priority
?
227 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
  • 2
10 Comments
 
LVL 20

Assisted Solution

by:BuggyCoder
BuggyCoder earned 668 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 86

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 1332 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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 86

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 1332 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
 
LVL 86

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 1332 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 668 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 86

Accepted Solution

by:
Mike Tomlinson earned 1332 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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

618 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