473,770 Members | 7,213 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Main Thread doesn't run?

15 New Member
This code C# is from online source but it was in console application so I modify to work on windows form just for learning on how to use threading.timer , but it doesn't work. Can anyone help me?

I would like the code below to display message to richtextbox while the timer object is not yet destroy so the main thread shouldn't run. When timer object is destroy, the main thread will start and display the last message, "Timer example done."


Can anyone tell me why the timer doesn't execute CheckStatus() because in that method has some message to display, but I don't see the message display at all.. Thanks in advance.
-------------------------------------------------------------------------------------------------
Expand|Select|Wrap|Line Numbers
  1.     class TimerExampleState
  2.     {
  3.         public int counter = 0;
  4.         public System.Threading.Timer tmr;
  5.     }
  6.  
  7.  
  8.     public partial class Form1 : Form
  9.     {
  10.         private string messageString = string.Empty;
  11.  
  12.         public Form1()
  13.         {
  14.             InitializeComponent();
  15.         }
  16.  
  17.  
  18.  
  19.         private void button1_Click(object sender, EventArgs e)
  20.         {
  21.             TimerExampleState s = new TimerExampleState();
  22.  
  23.             //create the delegate that invokes methods for the timer.
  24.             TimerCallback timerDelegate = new TimerCallback(CheckStatus);
  25.  
  26.             // Create a timer that waits one second, then invokes every second.
  27.             System.Threading.Timer timer = new System.Threading.Timer(timerDelegate, s, 1000, 1000);
  28.  
  29.             // Keep a handle to the timer, so it can be disposed.
  30.             s.tmr = timer;
  31.  
  32.             // The main thread does nothing until the timer is disposed.
  33.             while (s.tmr != null)
  34.                 Thread.Sleep(0);
  35.  
  36.             richTextBox1.AppendText("Timer example done.");
  37.         }
  38.  
  39.  
  40.         // The following method is called by the timer's delegate.
  41.         private void CheckStatus(Object state)
  42.         {
  43.             TimerExampleState s = (TimerExampleState)state;
  44.             s.counter++;
  45.             messageString = "Checking status: "+ s.counter;
  46.             RunMe();
  47.  
  48.             //After display message five times, wait for 10 seconds.
  49.             if (s.counter == 5)
  50.             {
  51.                 // Shorten the period. Wait 10 seconds to restart the timer.
  52.                 (s.tmr).Change(10000, 100);
  53.                 messageString = "changed...";
  54.  
  55.                 RunMe();
  56.             }
  57.  
  58.             if (s.counter == 10)
  59.             {
  60.                 messageString = "disposing of timer...";
  61.                 s.tmr.Dispose();
  62.                 s.tmr = null;
  63.  
  64.                 RunMe();
  65.             }
  66.  
  67.         }
  68.  
  69.         private void RunMe()
  70.         {
  71.             //----trying label1
  72.             if (label2.InvokeRequired)
  73.             {
  74.                 this.BeginInvoke(new MethodInvoker(RunMe));
  75.             }
  76.             else
  77.             {
  78.                 label2.Text = messageString;
  79.             }
  80.         }
  81.  
  82.     }
Aug 27 '08 #1
11 1484
Curtis Rutland
3,256 Recognized Expert Specialist
Please remember to use CODE tags when posting.

MODERATOR
Aug 27 '08 #2
winningElevent
15 New Member
Thanks, I was looking for the CODE tage too, but I didn't know that code tage is
Aug 27 '08 #3
Plater
7,872 Recognized Expert Expert
I am not sure what Thread.Sleep(0) would do, but it probably means it waits forever. Are you noticing your program just stops working?
Aug 27 '08 #4
winningElevent
15 New Member
Hmmm, when I run this program under console application because that is what originally written on console because I found it on google. According to the console application when I execute, the main thread should not start until the timer get destroy. So the Thread.sleep(0) just put the main thread to sleep, but I dont think it will sleep forever. So the program should display this phrase five time, messageString = "Checking status: "+s.counter , then after five time, it will change to display this phrase, messageString = "changed... " while waiting about 10seconds. When the s.counter reaches 10, the timer object gets destroyed that is when the main thread starts to run and display the last message, richTextBox1.Ap pendText("Timer example done.");
Aug 27 '08 #5
winningElevent
15 New Member
I am not sure what Thread.Sleep(0) would do, but it probably means it waits forever. Are you noticing your program just stops working?

Wait, wait, I was wrong. When I first executed the program, I didn't wait enough times to see the main thread running. When I execute the program, the program doesn't display anything which I'm not sure why it doesn't display anything because I put these three phrases for displaying.
Expand|Select|Wrap|Line Numbers
  1. messageString = "Checking status: "+ s.counter;
  2.  
Expand|Select|Wrap|Line Numbers
  1. messageString = "changed...";
  2.  
Expand|Select|Wrap|Line Numbers
  1. messageString = "disposing of timer...";
  2.  
Although none of them display, however the main thread seems to work because it doesn't execute this statement:
Expand|Select|Wrap|Line Numbers
  1. richTextBox1.AppendText("Timer example done.");
  2.  
until for quite a while which I approximate the time is almost the same amount of time it takes to get the timer object to destroyed.

Base on the while-condition that i have above:
Expand|Select|Wrap|Line Numbers
  1.             while (s1.tmr != null)
  2.                 Thread.Sleep(0);
  3.  
Those three phrases don't display but when I switch between != to ==, those three phrases display. Hmmm I don't undestand. It seems the timer doesn't get executed because the main thread doesn't run, but when the main thread runs, the timer is executed. But I thought timer is a different thread from the main thread, isn't it?
Aug 27 '08 #6
Plater
7,872 Recognized Expert Expert
Well, I bet if inside that while loop you added Application.DoE vents()
You would see the change.
Aug 27 '08 #7
winningElevent
15 New Member
Well, I bet if inside that while loop you added Application.DoE vents()
You would see the change.
oh my goodness thank you so much. Thank you, thank you. It works just like you said. If you don't mind, can you explain why Application.DoE vent() has to be in there and what for purpose? Hmmm what about console application, why it doesn't need to have Application.DoE vent() and it works?
Aug 27 '08 #8
Plater
7,872 Recognized Expert Expert
Application.DoE vents() tells the program to perform all pending windows messages (generally gui stuff). Your "gui thread" was sitting in that busy loop and never getting a chance to process its events.
Aug 27 '08 #9
winningElevent
15 New Member
Application.DoE vents() tells the program to perform all pending windows messages (generally gui stuff). Your "gui thread" was sitting in that busy loop and never getting a chance to process its events.
Oh I see. So I guess the console doesn't have any gui like form app. is that why it doesn't need DoEvent(), I assume.

Then System.Threadin g.Timer doesn't run on the gui thread?
Aug 27 '08 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

4
1670
by: Rhamphoryncus | last post by:
First a bit about myself. I've been programming in python several years now, and I've got several more years before that with C. I've got a lot of interest in the more theoretical stuff (language design, component architectures, etc). Of late my focus has been on concurrent operations (and on how to design a GUI architecture, but that's not what this post is about). I've looked at threads, and the inability to kill them easily was a...
23
6546
by: Jeff Rodriguez | last post by:
Here's what I want do: Have a main daemon which starts up several threads in a Boss-Queue structure. From those threads, I want them all to sit and watch a queue. Once an entry goes into the queue, grab it and run a system command. Now I want to make sure that system command doesn't hang forever, so I need some way to kill the command and have the worker thread go back to work waiting for another queue entry.
3
3584
by: Boniek | last post by:
Hi My main thread is waiting for data from database ( opened Sqlconnection etc) and my Main Form is also blocked. I have a ProgressBar on Status Bar which show to a user how percent data is loaded. I use ThreadTimer and Thread but I can't do anything because when a thread (or ThreadTimer) go to the line ProgressBar.PefromStep() then it stop on that line. I think it's work like that because the Main Thread (and main Form) is sleeping....
11
5081
by: objectref | last post by:
Hi to all, is there a way to get the window handle of the main window of an application or process ? For example, if someone opens Microsoft Word, he gets a window so he/she can write text. Spy++ gives that this window is called _Wwg. How we can get a handle to this window assuming that we do not know beforehand the name of the process,
5
9896
by: Hao L | last post by:
For example, void WorkerMethod() { ... UnregisterAllHotkeys();} void UnregisterAllHotKeys { for(...) {UnregisterHotKey(...);}} UnregisterHotKey is an API function that must be on the thread that RegisterHotKey was called in order to unregister any of the hot keys RegisterHotkey registered. ("The UnregisterHotKey function frees a hot key previously registered by the calling thread.") Is there any way to call UnregisterAllHotkeys, a...
6
5994
by: Joe Jax | last post by:
I have an object that spawns a worker thread to process one of its methods. That method processes methods on a collection of other objects. During this processing, a user may request to cancel the entire operation. I could request abort on the worker thread, but that is a) potentially messy, and b) not guaranteed to take immediate effect anyway. I would rather have some way of allowing the main thread to tell the worker thread that it...
9
1236
by: Tor Erik | last post by:
Hi, I've developed an application were I've used Tkinter for the GUI. When I ran the GUI in another thread than the main, it kept locking up. I experienced similar problems with Twisted. Both of these tools are event-based, so I guess that is the root of the problem...
0
1229
by: Lloyd Zusman | last post by:
I have a python-2.5 program running under linux in which I spawn a number of threads. The main thread does nothing while these subsidiary threads are running, and after they all complete, the main thread will then exit. I know that I can manage this through the use of Thread.join(), but when I do it as follows, the main thread doesn't respond to signals: import sys, time, signal, threading
6
2740
by: DaTurk | last post by:
I know in a WinForm you can check if an Invoke is inquired and invoke a method on the main thread. But can you do this in a class? Can I call Invoke(someMethod) in my asynch event handler? And if I can't do it this way, is there a way I can do it? Thanks.
0
9592
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9425
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10058
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10004
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9870
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8886
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7416
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
3972
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.