hi to all folks,
i want to create the following senario:
i have a T1 (Thread 1) that acts like http server that receives incoming
requests.
From that T1, i want to spawn from T1 to Tn thread jobs and beeing able to
be
notified when each of these threads finished it's job.
I would like to implement it with the functionality of the ThreadPool,
i also looked at WaitHandle, WaitAny etc etc.
I also noticed from the msdn example that if i use the AutoResetEvent. Set()
method, i just set the state of the event to signaled but i see no way of
quering this and find it's state so i can understand that it is completed
, and the WaitAll and WaitAny stuff just blocks my T1 so all or any Tn
finishes it's job.
But how i can automate this procedure and each thread notify the main T1 of
the completion of it's job ??
the following is from the msdn help:
using System;
using System.Threadin g;
public sealed class App {
// Define an array with two AutoResetEvent WaitHandles.
static WaitHandle[] waitHandles = new WaitHandle[] {
new AutoResetEvent( false),
new AutoResetEvent( false)
};
// Define a random number generator for testing.
static Random r = new Random();
static void Main() {
AutoResetEvent are = new AutoResetEvent( false);
are.Set
// Queue up two tasks on two different threads;
// wait until all tasks are completed.
DateTime dt = DateTime.Now;
Console.WriteLi ne("Main thread is waiting for BOTH tasks to complete.");
ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Do Task), waitHandles[0]);
ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Do Task), waitHandles[1]);
WaitHandle.Wait All(waitHandles );
// The time shown below should match the longest task.
Console.WriteLi ne("Both tasks are completed (time waited={0})",
(DateTime.Now - dt).TotalMillis econds);
// Queue up two tasks on two different threads;
// wait until any tasks are completed.
dt = DateTime.Now;
Console.WriteLi ne();
Console.WriteLi ne("The main thread is waiting for either task to
complete.");
ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Do Task), waitHandles[0]);
ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Do Task), waitHandles[1]);
int index = WaitHandle.Wait Any(waitHandles );
// The time shown below should match the shortest task.
Console.WriteLi ne("Task {0} finished first (time waited={1}).",
index + 1, (DateTime.Now - dt).TotalMillis econds);
}
static void DoTask(Object state) {
AutoResetEvent are = (AutoResetEvent ) state;
int time = 1000 * r.Next(2, 10);
Console.WriteLi ne("Performing a task for {0} milliseconds.", time);
Thread.Sleep(ti me);
are.Set();
}
}
thanks in advance fro any help 2 4716
objectref,
Instead of using events and whatnot, why not just have the DoWork method
call a function at the end to indicate that the task is done, and then
perform whatever work you need to do at that point? Unless you have a
thread somewhere else waiting on the fact that these tasks are done (which
you probably don't since you are servicing requests in separate threads
anyways), you shouldn't have a need for waiting on events.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
"objectref" <ob*******@medi atrel.com> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. .. hi to all folks,
i want to create the following senario: i have a T1 (Thread 1) that acts like http server that receives incoming requests. From that T1, i want to spawn from T1 to Tn thread jobs and beeing able to be notified when each of these threads finished it's job.
I would like to implement it with the functionality of the ThreadPool, i also looked at WaitHandle, WaitAny etc etc.
I also noticed from the msdn example that if i use the AutoResetEvent. Set() method, i just set the state of the event to signaled but i see no way of quering this and find it's state so i can understand that it is completed , and the WaitAll and WaitAny stuff just blocks my T1 so all or any Tn finishes it's job.
But how i can automate this procedure and each thread notify the main T1 of the completion of it's job ??
the following is from the msdn help:
using System; using System.Threadin g;
public sealed class App { // Define an array with two AutoResetEvent WaitHandles. static WaitHandle[] waitHandles = new WaitHandle[] { new AutoResetEvent( false), new AutoResetEvent( false) };
// Define a random number generator for testing. static Random r = new Random();
static void Main() { AutoResetEvent are = new AutoResetEvent( false); are.Set
// Queue up two tasks on two different threads; // wait until all tasks are completed. DateTime dt = DateTime.Now; Console.WriteLi ne("Main thread is waiting for BOTH tasks to complete."); ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Do Task), waitHandles[0]); ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Do Task), waitHandles[1]); WaitHandle.Wait All(waitHandles );
// The time shown below should match the longest task. Console.WriteLi ne("Both tasks are completed (time waited={0})", (DateTime.Now - dt).TotalMillis econds);
// Queue up two tasks on two different threads; // wait until any tasks are completed. dt = DateTime.Now; Console.WriteLi ne(); Console.WriteLi ne("The main thread is waiting for either task to complete."); ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Do Task), waitHandles[0]); ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Do Task), waitHandles[1]);
int index = WaitHandle.Wait Any(waitHandles ); // The time shown below should match the shortest task. Console.WriteLi ne("Task {0} finished first (time waited={1}).", index + 1, (DateTime.Now - dt).TotalMillis econds); }
static void DoTask(Object state) { AutoResetEvent are = (AutoResetEvent ) state; int time = 1000 * r.Next(2, 10); Console.WriteLi ne("Performing a task for {0} milliseconds.", time); Thread.Sleep(ti me); are.Set(); } } thanks in advance fro any help
Nicholas,
thanks for the reply.
The reason i cannot do what you suggest me, is that i want to keep track
from the main
thread of all the threads that i spawn, so to be able to stop a thread that
it stalls.
This is a runtime system i have build and there is a possibility for a give
request to
stall, that is, come into an endless loop and the Tn will be live forever.
So, i have to keep track of them and i want to identify and stop a nasty
thread.
This is the reason that i must keep track of the threads and they have to
notify, somehow,
the T1 for their completion status.
Imagine that every thread that i spawn, belongs to an array and when
it finish it's job, i remove it from the array.
Threads that remain in the array for a specified time, are consinered
"nasty" and
will be stop and removed from there...
Any thoughts on this ?
thanks again!
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om> wrote in
message news:ei******** ******@TK2MSFTN GP15.phx.gbl... objectref,
Instead of using events and whatnot, why not just have the DoWork method call a function at the end to indicate that the task is done, and then perform whatever work you need to do at that point? Unless you have a thread somewhere else waiting on the fact that these tasks are done (which you probably don't since you are servicing requests in separate threads anyways), you shouldn't have a need for waiting on events.
Hope this helps.
-- - Nicholas Paldino [.NET/C# MVP] - mv*@spam.guard. caspershouse.co m
"objectref" <ob*******@medi atrel.com> wrote in message news:%2******** ********@TK2MSF TNGP14.phx.gbl. .. hi to all folks,
i want to create the following senario: i have a T1 (Thread 1) that acts like http server that receives incoming requests. From that T1, i want to spawn from T1 to Tn thread jobs and beeing able to be notified when each of these threads finished it's job.
I would like to implement it with the functionality of the ThreadPool, i also looked at WaitHandle, WaitAny etc etc.
I also noticed from the msdn example that if i use the AutoResetEvent. Set() method, i just set the state of the event to signaled but i see no way of quering this and find it's state so i can understand that it is completed , and the WaitAll and WaitAny stuff just blocks my T1 so all or any Tn finishes it's job.
But how i can automate this procedure and each thread notify the main T1 of the completion of it's job ??
the following is from the msdn help:
using System; using System.Threadin g;
public sealed class App { // Define an array with two AutoResetEvent WaitHandles. static WaitHandle[] waitHandles = new WaitHandle[] { new AutoResetEvent( false), new AutoResetEvent( false) };
// Define a random number generator for testing. static Random r = new Random();
static void Main() { AutoResetEvent are = new AutoResetEvent( false); are.Set
// Queue up two tasks on two different threads; // wait until all tasks are completed. DateTime dt = DateTime.Now; Console.WriteLi ne("Main thread is waiting for BOTH tasks to complete."); ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Do Task), waitHandles[0]); ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Do Task), waitHandles[1]); WaitHandle.Wait All(waitHandles );
// The time shown below should match the longest task. Console.WriteLi ne("Both tasks are completed (time waited={0})", (DateTime.Now - dt).TotalMillis econds);
// Queue up two tasks on two different threads; // wait until any tasks are completed. dt = DateTime.Now; Console.WriteLi ne(); Console.WriteLi ne("The main thread is waiting for either task to complete."); ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Do Task), waitHandles[0]); ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Do Task), waitHandles[1]);
int index = WaitHandle.Wait Any(waitHandles ); // The time shown below should match the shortest task. Console.WriteLi ne("Task {0} finished first (time waited={1}).", index + 1, (DateTime.Now - dt).TotalMillis econds); }
static void DoTask(Object state) { AutoResetEvent are = (AutoResetEvent ) state; int time = 1000 * r.Next(2, 10); Console.WriteLi ne("Performing a task for {0} milliseconds.", time); Thread.Sleep(ti me); are.Set(); } } thanks in advance fro any help
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Valkyrie |
last post by:
Refering to the following codes I found, there is nothing displayed in the
console, may I ask why?
def thrd(param): # the thread worker function
print "Received",param
import thread
for i in range(5): # start five threads passing i to each one
thread.start_new_thread(thrd,(i,))
|
by: Alec Wysoker |
last post by:
I have several programs that have two or more threads. The threads that are not the main thread are daemon threads, i.e. the fact that they are running should not stop the program from terminating if the main thread (the only non-daemon thread) terminates. I do not join to these threads, but just run off the end of the main module to terminate the program. I'm using Python 2.3.4. I occasionally get the following error:
Traceback (most...
|
by: Matthew Groch |
last post by:
Hi all,
I've got a server that handles a relatively high number of concurrent
transactions (on the magnitude of 1000's per second). Client
applications establish socket connections with the server. Data is
sent and received over these connections using the asynchronous model.
The server is currently in beta testing. Sporadically over the course
of the day, I'll observe the thread count on the process (via perfmon)
start climbing....
|
by: VMI |
last post by:
In the following code, how can I display the MessageBox once MyThread has
finished executing? updateFiles method copies 5 humongous files to the HDD
but for some reason, the MessageBox is displayed before updateFles has
finished executing.
This is the code:
MyThread = new Thread(new ThreadStart (updateFiles));
MyThread.Start();
MessageBox.Show("Program has ended");
|
by: Teis Draiby |
last post by:
In an application manipulating streaming video and 3D stuff I want to
implement mutithreading to ensure a decent UI response time.
Since my application is very speed critical I want to use the most efficient
synchronization of the shared data objects. What would that be in this case?
I think there's a very simple answer to this, but I am somewhat confused by
the different methods available.
The data I need to transfer between threads...
| |
by: Lalatendu Das |
last post by:
Dear friends,
I am getting a problem in the code while interacting with a nested
Do-while loop
It is skipping a scanf () function which it should not. I have written
the whole code below. Please help me in finding why such thing is
happening and what the remedy to it is. Kindly bear with my English.
int
main ()
|
by: gates.liu |
last post by:
Sir:
I have used FileSystemWathcher(.NET class) to monitor file change
envent.The code as list:
......................
int i=0; //Counter for Changed event after FileCreated event
private void IntializeFileSystemWatcher()
{
//Create File System Watcher in mypath for new files
|
by: HairlipDog58 |
last post by:
Hello,
There are several 'cross-thread operation not valid' exception postings in
the MSDN discussion groups, but none address my exact situation.
I have authored a .NET component in Visual C# .NET 2003 that is capable of
firing several types of events to notify user of errors, data changes, etc.
The component uses a thread to perform background communications and if there
is an error or data-change fires an event to notify the user....
|
by: sethwai |
last post by:
Hi,
I have a nightly script that executes inplace reorgs allow write
access for several tables after a previous script does a large number
of delete operations. It usually has been executing fine. The other
night 3 of them failed due to the log file system filling up. I
resumed them individually and they all completed successfully.
To eliminate the log space problem I changed the script to wait for
one to complete before startng...
|
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:
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: 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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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: 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...
| |