CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11

Thread: delay

  1. #1
    Join Date
    Apr 2012
    Posts
    25

    delay

    Hello , I am beginer in c++ as i started few days ago and i find it hard to understand most of syntax.

    What i should use to make part of code do a calculation 1 time and after that not repeat actions?
    What should i use to make part of code to repeat itself?
    I am trying to make a widely customizable delay timer of 3sec out of QueryPerformanceFreqency and QueryPerformanceCounter by first calculating QueryPerformanceFreqency*3+QueryPerformanceCounter , then not repetaing it anymore and later it should start to compare results from QueryPerformanceFreqency*3+QueryPerformanceCounter to QueryPerformanceCounter. So if value becaomes bigger it would start to do delayed task.

    program, it compiles under visual studio 2010 but i am not able to make a delay as i was hoping for because of too little understanding how to manipulate values in code.

    idea is that by pressing checkbox1 it would make aaaaaaa appear with 3sec delay.

    Code:
    #pragma once
    #include <iostream>
    #include <windows.h>                // for Windows APIs
    
    namespace timerfinal {
    
    	using namespace System;
    	using namespace System::ComponentModel;
    	using namespace System::Collections;
    	using namespace System::Windows::Forms;
    	using namespace System::Data;
    	using namespace System::Drawing;
    
    	/// <summary>
    	/// Summary for Form1
    	/// </summary>
    	public ref class Form1 : public System::Windows::Forms::Form
    	{
    	public:
    		Form1(void)
    		{
    			InitializeComponent();
    			//
    			//TODO: Add the constructor code here
    			//
    		}
    
    	protected:
    		/// <summary>
    		/// Clean up any resources being used.
    		/// </summary>
    		~Form1()
    		{
    			if (components)
    			{
    				delete components;
    			}
    		}
    	private: System::Windows::Forms::CheckBox^  checkBox1;
    	private: System::Windows::Forms::Label^  label1;
    	protected: 
    
    	private:
    		/// <summary>
    		/// Required designer variable.
    		/// </summary>
    		System::ComponentModel::Container ^components;
    
    #pragma region Windows Form Designer generated code
    		/// <summary>
    		/// Required method for Designer support - do not modify
    		/// the contents of this method with the code editor.
    		/// </summary>
    		void InitializeComponent(void)
    		{
    			this->checkBox1 = (gcnew System::Windows::Forms::CheckBox());
    			this->label1 = (gcnew System::Windows::Forms::Label());
    			this->SuspendLayout();
    			// 
    			// checkBox1
    			// 
    			this->checkBox1->AutoSize = true;
    			this->checkBox1->Location = System::Drawing::Point(44, 12);
    			this->checkBox1->Name = L"checkBox1";
    			this->checkBox1->Size = System::Drawing::Size(80, 17);
    			this->checkBox1->TabIndex = 0;
    			this->checkBox1->Text = L"checkBox1";
    			this->checkBox1->UseVisualStyleBackColor = true;
    			this->checkBox1->CheckedChanged += gcnew System::EventHandler(this, &Form1::checkBox1_CheckedChanged);
    			// 
    			// label1
    			// 
    			this->label1->AutoSize = true;
    			this->label1->Location = System::Drawing::Point(41, 32);
    			this->label1->Name = L"label1";
    			this->label1->Size = System::Drawing::Size(35, 13);
    			this->label1->TabIndex = 1;
    			this->label1->Text = L"label1";
    			// 
    			// Form1
    			// 
    			this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
    			this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
    			this->ClientSize = System::Drawing::Size(158, 77);
    			this->Controls->Add(this->label1);
    			this->Controls->Add(this->checkBox1);
    			this->Name = L"Form1";
    			this->Text = L"Form1";
    			this->ResumeLayout(false);
    			this->PerformLayout();
    
    		}
    #pragma endregion
    	private: System::Void checkBox1_CheckedChanged(System::Object^  sender, System::EventArgs^  e) {
    
    
    
    
    
    
    {
        LARGE_INTEGER freq;            // ticks per second
        LARGE_INTEGER time;            //count+needed time   
        LARGE_INTEGER count;           //all ticks
    
          // get ticks per second
        QueryPerformanceFrequency(&freq);
    	  // count for ending
        QueryPerformanceCounter(&count);
          //ticks needed
        time.QuadPart = (freq.QuadPart*3) + count.QuadPart;      
        
        while (count.QuadPart >= time.QuadPart){             
        label1->Text = "aaaaaaaaa";
                }
    }
    
    
    
    
    
    
    
    
    
    			 }
    	};
    }
    problem is in this part, i was hoping it to work as delay.

    as far as i am able to understrand
    QueryPerformanceFrequency should mean how many numbers per sec
    QueryPerformanceCounter should be how many numbers have passed


    i am not sure how to make it compare (count.QuadPart >= time.QuadPart) so if value becomes equal or bigger it would do task.

    time.QuadPart = (freq.QuadPart*3) + count.QuadPart;
    this calculation may only be needed once , i am not sure but maybe this repeats itself with my current code.

    Sleep() freezes all, tryed to understand others as well but too complicated to understand.
    Code:
    {
        LARGE_INTEGER freq;            // ticks per second
        LARGE_INTEGER time;            //count+needed time   
        LARGE_INTEGER count;           //all ticks
    
          // get ticks per second
        QueryPerformanceFrequency(&freq);
    	  // count for ending
        QueryPerformanceCounter(&count);
          //ticks needed
        time.QuadPart = (freq.QuadPart*3) + count.QuadPart;      
        
        while (count.QuadPart >= time.QuadPart){             
        label1->Text = "aaaaaaaaa";
                }
    }
    Last edited by 1248; April 22nd, 2012 at 12:11 PM.

  2. #2
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Re: delay

    Quote Originally Posted by 1248 View Post
    What i should use to make part of code do a calculation 1 time and after that not repeat actions?
    Well, I'm not entirely sure I get your actual intention from your description, I think what you need still is a timer. While that is usually used to trigger repeated actions at a certain time interval, it can be used to triger a one-shot action after a certain delay as well. A scenario where I used this technique is discussed in http://forums.codeguru.com/showthread.php?t=506653, and the test code I used to play with while writing the posts to that thread is attached to http://forums.codeguru.com/showthread.php?p=2032054 (in a thread on a completely different topic, though).

    More information on timers can be found using a forum search. By now there should be at least 14 threads that at least touched that topic (in a more or less complex context), in which I participated myself, in this forum section here.

    Having a closer look at your checkBox1_CheckedChanged() event handler, you may notice that it actually sets the text of the label to "aaa..." immediately, and then repeats that for three seconds at the maximum possible rate. This repitition isn't observable on the GUI since your code repeatedly sets the text to the same value. You may easily verify that using the debugger, however.

    This is closer to what you actually want to do:

    Code:
    private: System::Void checkBox1_CheckedChanged(System::Object^  sender, System::EventArgs^  e)
             {
               LARGE_INTEGER freq;            // ticks per second
               LARGE_INTEGER time;            //count+needed time   
               LARGE_INTEGER count;           //all ticks
    
               // get ticks per second
               QueryPerformanceFrequency(&freq);
               // count for ending
               QueryPerformanceCounter(&count);
               //ticks needed
               time.QuadPart = (freq.QuadPart*3) + count.QuadPart;
    
               while (count.QuadPart >= time.QuadPart);  // Empty loop spinning for 3 secs doing nothing
               label1->Text = "aaaaaaaaa";               // ... and only _then_ set the label's text
             }
    But effectively this is (almost) identical to what this would do:

    Code:
    private: System::Void checkBox1_CheckedChanged(System::Object^  sender, System::EventArgs^  e)
             {
               Threading::Thread::Sleep(3000);
               label1->Text = "aaaaaaaaa";
             }
    You already noticed that this freezes the GUI because it blocks the thread servicing it, which the timer approach would not do. And the Sleep() approach even is the much better one of the two: It's resource-conservative and doesn't burn each and every CPU clock cycle it can get hold of, just for doing three seconds of nothing.

    Code:
    #include <windows.h>                // for Windows APIs
    While it is possible to use Windows API (and other native code) in C++/CLI, that should be avoided whenever possible. It tends to (unnecessrily) complicate things, especially for beginners.
    Last edited by Eri523; April 24th, 2012 at 06:09 PM. Reason: Code correction in second snippet (see posts #7 to 9) :o
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  3. #3
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Red face Re: delay

    Oops! The first code snippet from my last post actually should rather have been something like this:

    Code:
    private: System::Void checkBox1_CheckedChanged(System::Object^  sender, System::EventArgs^  e)
             {
               LARGE_INTEGER freq;            // ticks per second
               LARGE_INTEGER time;            //count+needed time   
               LARGE_INTEGER count;           //all ticks
    
               // get ticks per second
               QueryPerformanceFrequency(&freq);
               // count for ending
               QueryPerformanceCounter(&count);
               //ticks needed
               time.QuadPart = (freq.QuadPart*3) + count.QuadPart;
    
               while (count.QuadPart >= time.QuadPart) {  // Keep spinning, re-querying the performance counter until 3 secs have elapsed
                 QueryPerformanceCounter(&count);
               }
               label1->Text = "aaaaaaaaa";                // ... and only _then_ set the label's text
             }
    Carelessly, I somehow mistook count.QuadPart for a .NET object's property that may change "on its own", while plain primitive type fields of a POD struct, which it actually is, usually don't (unless multithreding is involved). Actually, it was that question that you asked over there in the VC++ section that made me rethink it and find my mistake.

    There may be even more silly mistakes, since I didn't test that code, nor ever did use this performance counter or the LARGE_INTEGER struct (directly) myself.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  4. #4
    Join Date
    Apr 2012
    Posts
    25

    Re: delay

    Thanks for taking time to help.
    I will try to learn debugging today so i can see how numbers change to look where problem is.

    Do i need to use this to ensure it calculates once only or it already does it once?
    if (1 > time.QuadPart)(
    time.QuadPart = (freq.QuadPart*300) + count.QuadPart);

  5. #5
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Re: delay

    Quote Originally Posted by 1248 View Post
    I will try to learn debugging today so i can see how numbers change to look where problem is.
    Well, the problem here is rather obvious and also I told you what it is. However, learning debugging always is a good idea and will probably give you a more hands-on perception of the problem here. But there will come much more exciting things to discover by debugging...

    Do i need to use this to ensure it calculates once only or it already does it once?
    if (1 > time.QuadPart)(
    time.QuadPart = (freq.QuadPart*300) + count.QuadPart);
    No. You definitely do need a timer here. It may look more complicated, but only on first sight. And the other two variants discussed both are no alternatives: They both block the GUI thread for three seconds.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  6. #6
    Join Date
    Jan 2010
    Posts
    1,133

    Re: delay

    Quote Originally Posted by 1248 View Post
    I will try to learn debugging today so i can see how numbers change to look where problem is.
    As Eri523 said, knowing how to debug is very important. And the best part is: the basics of it aren't that hard at all.

    You just put a breakpoint somewhere in your code, on a line you know is gonna get hit - often you'll be interested in a specific line of code.

    Then you start debugging (F5, assuming you're using VS), and the execution will break there.

    At that point, you can examine variables, by hovering your mouse over them, and a bunch of other stuff you can read about somewhere else.
    You can then go step-by-step, line-by-line, through your code. Use "Step Over" - F10, to simply go line by line without getting inside function calls, or "Step Into" - F11, to step inside functions when possible.

    This way you can directly observe what is happening as your program executes. When done, you can either continue normal execution (F5), stop everything and exit (Shift + F5), or restart (Ctrl + Shift + F5).

    Note that there are also toolbar buttons and menu commands for all of these.

    That's the basic usage, but the debugger can a lot more. There's the Watch window, the Call Stack, Locals window, you can evaluate expressions, even change variable values, etc...

  7. #7
    Join Date
    Apr 2012
    Posts
    25

    Re: delay

    I think this code is not doing its job and i have no idea how to make it work so il use thisone.
    {
    Threading::Sleep(3000);
    label1->Text = "aaaaaaaaa";
    }

  8. #8
    Join Date
    Apr 2012
    Posts
    25

    Re: delay

    i get this error

    1>c:\users\--\documents\visual studio 2010\projects\timer final\timer final\Form1.h(95): error C2039: 'Sleep' : is not a member of 'System::Threading'


    Is ther any sleep way that wont freeze all?

  9. #9
    Join Date
    Jan 2010
    Posts
    1,133

    Re: delay

    That's because Threading is a namespace.
    You should write:
    System::Threading::Thread::Sleep(3000);

    Or, if you add "using namespace System::Threading;", just:
    Thread::Sleep(3000);

    Sleep causes the thread to block for the specified amount of time. For UI applications, if this happens on the UI thread, the application will freeze. If it happens on a separate thread, only that thread will block, but the application will stay responsive.

    However, be careful if you're not experienced with multithreading, as with more than one thread, there's always potential for problems (race conditions, invalid state, deadlocks...).
    You can also, on one thread, at regular time intervals, also measure time elapsed since the last call, and choose to do no additional processing if the total time is less than some set amount.

  10. #10
    Join Date
    Apr 2012
    Posts
    25

    Re: delay

    Thanks for taking time to write answers to those beginner questions.
    As far as i have understood it is probably possible to delay part of code by code but it requires more knowledge than i have found so far.

  11. #11
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Re: delay

    Quote Originally Posted by 1248 View Post
    As far as i have understood it is probably possible to delay part of code by code [...].
    Your wording of that question is rather vague, but I think it can be answered with yes. However, not anything that can be done should be done, which is part of what the discussion in this thread so far has been about.

    You seem pretty reluctant about using the timer, but why? It's not really so complicated...
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured