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.
------------------------------------------------------------------------------------------------- - class TimerExampleState
-
{
-
public int counter = 0;
-
public System.Threading.Timer tmr;
-
}
-
-
-
public partial class Form1 : Form
-
{
-
private string messageString = string.Empty;
-
-
public Form1()
-
{
-
InitializeComponent();
-
}
-
-
-
-
private void button1_Click(object sender, EventArgs e)
-
{
-
TimerExampleState s = new TimerExampleState();
-
-
//create the delegate that invokes methods for the timer.
-
TimerCallback timerDelegate = new TimerCallback(CheckStatus);
-
-
// Create a timer that waits one second, then invokes every second.
-
System.Threading.Timer timer = new System.Threading.Timer(timerDelegate, s, 1000, 1000);
-
-
// Keep a handle to the timer, so it can be disposed.
-
s.tmr = timer;
-
-
// The main thread does nothing until the timer is disposed.
-
while (s.tmr != null)
-
Thread.Sleep(0);
-
-
richTextBox1.AppendText("Timer example done.");
-
}
-
-
-
// The following method is called by the timer's delegate.
-
private void CheckStatus(Object state)
-
{
-
TimerExampleState s = (TimerExampleState)state;
-
s.counter++;
-
messageString = "Checking status: "+ s.counter;
-
RunMe();
-
-
//After display message five times, wait for 10 seconds.
-
if (s.counter == 5)
-
{
-
// Shorten the period. Wait 10 seconds to restart the timer.
-
(s.tmr).Change(10000, 100);
-
messageString = "changed...";
-
-
RunMe();
-
}
-
-
if (s.counter == 10)
-
{
-
messageString = "disposing of timer...";
-
s.tmr.Dispose();
-
s.tmr = null;
-
-
RunMe();
-
}
-
-
}
-
-
private void RunMe()
-
{
-
//----trying label1
-
if (label2.InvokeRequired)
-
{
-
this.BeginInvoke(new MethodInvoker(RunMe));
-
}
-
else
-
{
-
label2.Text = messageString;
-
}
-
}
-
-
}
11 1484
Please remember to use CODE tags when posting.
MODERATOR
Thanks, I was looking for the CODE tage too, but I didn't know that code tage is
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?
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.");
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. -
messageString = "Checking status: "+ s.counter;
-
-
messageString = "changed...";
-
-
messageString = "disposing of timer...";
-
Although none of them display, however the main thread seems to work because it doesn't execute this statement: -
richTextBox1.AppendText("Timer example done.");
-
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: -
while (s1.tmr != null)
-
Thread.Sleep(0);
-
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?
Plater 7,872
Recognized Expert Expert
Well, I bet if inside that while loop you added Application.DoE vents()
You would see the change.
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?
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.
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?
Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
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.
|
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....
|
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,
|
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...
| |
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...
|
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...
|
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
|
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.
|
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...
|
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,...
| |
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...
|
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,...
|
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...
|
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...
|
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...
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |