473,800 Members | 2,607 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 5439
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
8516
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
3059
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
13402
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
5343
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
2209
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
2576
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
2281
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
10501
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
10273
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
10250
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
10032
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
9085
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
7574
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...
0
6811
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
5603
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3764
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.