473,811 Members | 3,213 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

using ElapsedEventHan dler and Label

Its supposed to be a very simple program, with a class to display the
updated current time every second (CAnalogTime) inside a Label in my
form, using ElapsedEventHan dler from System.Timers;

The event is working, because the displaybox will show up every second
like requested.
Although the label (which i was able to initialize with a value), wont
update itself in this event.

Any ideas?

Thanx
--------------------------

public class CAnalogTime
{
public System.Timers.T imer myTimer;
public MainForm myForm;

public CAnalogTime( MainForm inForm)
{

myForm = inForm;
// There, the label will update normally ---->
myForm.label1.T ext = "dfdstime";
myTimer = new System.Timers.T imer();
myTimer.Interva l = 1000;
myTimer.Enabled = true;
myTimer.Elapsed += new ElapsedEventHan dler(myForm.Che ckInterval);
myTimer.Start() ;
}
}

public partial class MainForm
{
[STAThread]
public static void Main(string[] args)
{
Application.Ena bleVisualStyles ();
Application.Set CompatibleTextR enderingDefault (false);
Application.Run (new MainForm());
}
public MainForm()
{
InitializeCompo nent();
CAnalogTime myAnalogClock = new CAnalogTime( this);
}
public void CheckInterval(o bject sender,
System.Timers.E lapsedEventArgs e)
{
// But here the label wont update
this.label1.Tex t = DateTime.Now.To LongTimeString( );
// And strangely, the textbox will display every second :
MessageBox.Show ("toto");
}
}
--------------------------

Mar 27 '06 #1
3 5441
The following should work BUT PLEASE READ the following paragraph:
after your this.label1.Tex t = DateTime.Now.To LongTimeString( ); add the
following
this.label1.Ref resh();
or
Application.DoE vents();

Application DoEvents() will allow your app to yield to allow Windows to
process any pending events such as redrawing invalid parts of the
screen.

*** MULTI-THREADING ISSUES ***
One of the most important things to bear in mind with multithreading is
that you MUST ONLY communicate with control using the thread that
created, ie your main app. By using a thread from the ThreadPool,
created by using the Timer class from System.Timers class you have
created a new thread and have borken that rule.

It might be OK with a little app but can create subtle reliability
issues that are really hard to track down and replicate.

There's loads of good info around about this subject. I'd also
recommend .NET Multhreading by Alan L Dennis (ISBN 1-930110-54-5)

The quickest answer is to loook at the InvokeRequired property on
this.label1 to see if you're in a different thread and use
this.label1.Inv oke if you are. Here's the code you could try:

public void CheckInterval(o bject sender, System.Timers.E lapsedEventArgs
e)
{
InvokeUpdateLab el();
}
private void InvokeUpdateLab el()
{
if (this.label1.In vokeRequired)
{
this.label1.Inv oke(new MethodInvoker(I nvokeUpdateLabe l));
}
else
{
this.label1.Tex t = DateTime.Now.To LongTimeString( );
this.label1.Ref resh();
}
}

You can see that it just reinvokes itself in the correct thread

Jason

Mar 27 '06 #2
>Any ideas?

I suggest you use the System.Windows. Forms.Timer component instead.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Mar 27 '06 #3
>I'd suggest you use the System.Windows. Forms.Timer component instead.
Good point, it will run be in the same thread so need to worry about
Invoke/InvokeRequired.

But if CheckInterval() starts to take more than a few seconds to run
(as these things have a tendency to do the more they get developed)
you'll end up blocking the main thread resulting in a slow UI and hence
slow redrawing of thr screen

Mar 28 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
8517
by: clintonG | last post by:
Briefly stated, my problem is accessing and 'setting' properties of a label control declared in the template of another control noting that the other control is an instance of the beta 2 DetailsView control which supports a PagingTemplate. Somewhere I grabbed some declarations for a PagerTemplate to display paging as: <<First < Prev Next> Last>>
2
3061
by: DaveF | last post by:
public void StartTimer() { System.Timers.Timer myTimer = new System.Timers.Timer(); myTimer.Interval = Convert.ToDouble(ConfigurationSettings.AppSettings); myTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.myTimer_Elapsed); myTimer.Enabled = true; }
1
13403
by: Max Adams | last post by:
Using System.Timers.ElapsedEventHandler to specify a method and and ElapsedEventArgs object I've trawled the internet looking for some help on this topic. What I want to do is, every x seconds call function y with some parameters. Simple. The ElapsedEventArgs paramerter I want to pass in is an object "c" of a custom type. The following does not work: Clock.Elapsed += new System.Timers.ElapsedEventHandler( OnTimer, new
5
2155
by: ElanKathir | last post by:
Hi ! I wrote one code for Send the E-mail, But that code have some problem , So please help me Here i paste my code and Error: Error: Server Error in '/Elan_Sample' Application. --------------------------------------------------------------------------------
3
5346
by: Rob | last post by:
Hi all, I am having trouble converting the code below (found on http://vbnet.mvps.org/index.html?code/core/sendmessage.htm) into a format that will work using vb .NET. Can anyone have a look at it and let me know what I need to change. I have tried changing the "hwnd" type into intptr's but there seem to be other problems too, like it won't allow "lParam As Any" to be declared.
8
2416
by: acb | last post by:
Hi, I wrote a DLL Component (using Visual Studio 2005) and managed to include it into a C# Console application. I am now trying to include this component into a Web project. I copy the DLL into the bin directory but am not able to progress. Can anyone please guide me to an online tutorial on the subject. Thanks,
0
2210
by: Metal2You | last post by:
I'm working on an ASP.NET 2.0 application in Visual Studio 2005 that accesses a Sybase database back end. We're using Sybase SQL Anywhere 9.0.2.3228. I have installed and registered the Sybase .NET 2.0 DataProvider (iAnywhere.Data.AsaClient.dll) into the GAC so it can be used in the ProviderName property of a SQLDataSource and loads properly at run time. The application I'm writing is a bit more complex than the example I'm about to...
0
2579
by: Eugene Anthony | last post by:
The problem with my coding is that despite removing the records stored in the array list, the rptPages repeater control is still visible. The rptPages repeater control displayes the navigation link (1,2,3 so on). The code can be found in SubscriptionCart.aspx.cs. Default.aspx ------------
6
2284
by: IReallyNeedHelp | last post by:
I have saved the questions using AddQuestion.aspx page i have created but i don't know how to display it and calculate their score. this is the formview i have done, but there is some error <asp:FormView ID="FormView1" runat="server" DataKeyNames="QuestionID" DataSourceID="SqlDataSource1" Width="151px" AllowPaging="True"> <EditItemTemplate> QuestionID: ...
0
9734
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
10652
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10395
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...
0
10137
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
6895
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5700
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4346
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
3874
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3026
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.