473,473 Members | 2,126 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Asynchronous threads returning a result

132 New Member
Hello everybody,

I'm currently trying to get into multithreading to take care of my recurring tasks.

In some cases I need to perform tasks recurring for the entire duration of which the application is running.

One simple example is to display the current time.

I could just use a simple timer but that's probably not best practice. So I understand that I need to use a separate thread to do this. And since I need this clock to be pretty accurate I probably should assign a single thread to this one process in stead of using the thread pool and I would need to use it asynchronously so that the UI is not waiting for the separate thread to finish.

So I'm thinking of creating a process where I get the time from the pc and I extract the hours, minutes and seconds from it. Then I put in a thread.sleep for 100 ms and execute it again. In order for me to control the execution I'm also thinking of putting in a start and a stop-method.
Starting would be pretty straightforward, when you invoke the thread, that's your start but the problem is how to stop it?

I know I probably should be using the BeginInvoke, EndInvoke and IAsyncResult to achieve all this but I'm not sure how to get the pieces working together.

Expand|Select|Wrap|Line Numbers
  1. while(clockActivated)
  2. {
  3.   string currentTime;
  4.   currentTime = DateTime.Now.ToString("HH:mm:ss tt");
  5.   lblClock.Text = currentTime;
  6.   Thread.Sleep(10);
  7. }
  8.  
So basically my questions are:
- How can I start a thread which runs continuously?
- How can I pass the result back to a label on my form?
- How can I stop the thread which is in a continuous loop?

I hope some here can help me.
Thanks,
Kenneth
Oct 6 '13 #1
3 1998
Joseph Martell
198 Recognized Expert New Member
You have several options, but which one is best is really going to depend on exactly what you are trying to accomplish, how precise your timing needs to be, and what version of .Net you are using. New parallel processing classes were introduced with 4.0, I believe.

I would probably use System.Timers.Timer for this task (this is NOT System.Windows.Forms.Timer). It has several advantages. The timing is very accurate, so you shouldn't have any problems with missed updates. Also, the interface is pretty straight-forward and easy to use. Finally, you can cause it to execute code on the same thread as the UI, so updating UI elements becomes much easier.

The thing to remember is that just because you have started a thread doesn't mean you have to relinquish control of that thread in other areas of your code. In the following example, the form load event defines and starts the updater thread. Notice that the variable is actually defined at the class level, not inside the form load event. This makes it accessible everywhere in the form. The thread is stopped when someone clicks the stop button. The timer event handler does all of the updating and because the SynchronizingObject was set to the form itself the event handler is executing on the UI thread:

Expand|Select|Wrap|Line Numbers
  1.         private System.Timers.Timer _updater = null;
  2.         private void frmTest_Load(object sender, EventArgs e)
  3.         {
  4.             _updater = new System.Timers.Timer(100);
  5.             _updater.SynchronizingObject = this;
  6.             _updater.AutoReset = true;
  7.             _updater.Elapsed += new System.Timers.ElapsedEventHandler(_updater_Elapsed);
  8.             _updater.Start();
  9.         }
  10.  
  11.         void _updater_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  12.         {
  13.             lblClock.Text = DateTime.Now.ToString("HH:mm:ss tt");
  14.         }
  15.  
  16.         private void btnStopTimer_Click(object sender, EventArgs e)
  17.         {
  18.             _updater.Stop();
  19.         }
  20.  
Check out this post for some interesting information on the different timers available (an older article, but still good):
http://msdn.microsoft.com/en-us/magazine/cc164015.aspx
Oct 7 '13 #2
Cainnech
132 New Member
Hello Joseph,

Thanks for yor reply and the sample code.
I was aware that Timer class executes the timer itself on another thread, but in the example you gave, the _updater_Elapsed is still executed on the UI-thread and not on the timer thread, is that correct?

Because in this case it's a simple clock I want to display but there's a case where I need to poll a webservice every two seconds, which returns data in an XML or JSON format, which I need to process. I can't have it do that on my UI-thread or it will make my UI unresponsive.
Oct 7 '13 #3
Joseph Martell
198 Recognized Expert New Member
You are correct, but the reason it executes on the UI thread is specifically because of line 5 in my example code:
Expand|Select|Wrap|Line Numbers
  1. _updater.SynchronizingObject = this;
Using a synchronizing object like the windows form ('this' points to the containing form) causes the Elapsed event handler to be executed on the same thread as the UI. Leaving the Synchronizing Object set to null means that the event handler will execute on a separate thread. That is one of the places where the differences between System.Windows.Forms.Timer and System.Timers.Timer really shows up.

Two other points, since you mentioned web services:
  1. You should be able to use asynchronous calls to the web service if you are using WCF. Just add an event handler for when the call returns and then you don't have to really worry about holding up your UI thread because you blocked an a web service call. (Click on "Advanced" when adding the service reference and there should be a check box for "Generate asynchronus operations" in VS 2008)
  2. If you want to handle the multithreaded call to a web service yourself, you should disable the recurring execution of the web service thread at the start of your event handler (and re-enable it just before the end). If the web service takes a long time to respond for some reason you could have a pile up of Elapsed event handlers executing at the same time. That would be a lot of processing for not much reward.
Oct 7 '13 #4

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

Similar topics

2
by: Brian Tkatch | last post by:
DB2/SUN 8.1.6 Using the client and CREATEing a PROCEDURE with a one-character name and DECLAREing a CURSOR using WITH RETURN TO CLIENT, does not result in a RESULT SET being shown. CREATE...
33
by: Chris Croughton | last post by:
I notice the real reason for not posting "off-topic" here is that the result will be a long thread on whether the matter is off-topic or not -- caused by the very people who claim that they don't...
2
by: Darryl A. J. Staflund | last post by:
Hi there, Can anyone tell me why invoking a single SQL insert statement (well, rather, a method that performs a SQL insert) using an asynchronous delegate should result in twice the number of...
10
by: [Yosi] | last post by:
I would like to know how threads behavior in .NET . When an application create 4 threads for example start all of them, the OS task manager will execute all 4 thread in deterministic order manes,...
3
by: Keith Mills | last post by:
Hello, please find attached a basic outline of what I am attempting to accomplish... basically I want to create a number of THREADS (which I can do fine), but I then need a method for them to be...
1
by: fortepianissimo | last post by:
I have a simple xmlrpc server/client written in Python, and the client throws a list of lists to the server and gets back a list of lists. This runs without a problem. I then wrote a simple Java...
0
by: adougall | last post by:
I would like to know what the outcome was on the topic for Nested Stored Procedure returning result sets in DB2 on AS/400 was. I am getting the same problem RESULT_SET_LOCATOR in *LIBL type *SQLUDT...
4
by: Marcus Alves Grando | last post by:
Hello list, I have a strange problem with os.walk and threads in python script. I have one script that create some threads and consume Queue. For every value in Queue this script run os.walk()...
2
by: Steve Harclerode | last post by:
Hi all, I have a web application that uploads a file into a SQL database as a stream of bytes. On another page of the app, I retrieve the same byte stream from SQL, and my ultimate goal is...
0
by: sfurst | last post by:
I have stumbled across a very strange issue. My COBOL program was issuing a Row not found error, and returning the conditions back to me. I used these conditions and pulled the same query with AQT...
0
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,...
0
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,...
1
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...
0
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...
0
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,...
1
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
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 ...
1
muto222
php
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.