473,729 Members | 2,272 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Thread question - I know something is not done right.

ok This is my main. Pretty much it goes through each category and
starts up 4 worker threads that then ask for groups to gether from. My
problem is that when the thread gets done it keeps the mysql
connections open so I end up with quite a few at the end. Is there a
different way that I should do this?

class Program
{
static string[] categories = { "emulation" , "audio" ,
"console" , "anime" , "xxx" , "tv" , "pictures" , "video" };

static void Main(string[] args)
{
string proc = Process.GetCurr entProcess().Pr ocessName;
// get the list of all processes by that name
Process[] processes = Process.GetProc essesByName(pro c);
// if there is more than one process...
if (processes.Leng th 1)
{
//MessageBox.Show ("Applicatio n is already running");
return;
}
else
{
for (int x = 0; x < categories.Leng th; x++)
{
MasterList master = new MasterList();
Groups groups = new Groups(categori es[x]);
WorkerClass WC1 = new WorkerClass(mas ter, groups);
WorkerClass WC2 = new WorkerClass(mas ter, groups);
WorkerClass WC3 = new WorkerClass(mas ter, groups);
WorkerClass WC4 = new WorkerClass(mas ter, groups);
Thread Worker1 = new Thread(new
ThreadStart(WC1 .Start));
Thread Worker2 = new Thread(new
ThreadStart(WC2 .Start));
Thread Worker3 = new Thread(new
ThreadStart(WC3 .Start));
Thread Worker4 = new Thread(new
ThreadStart(WC4 .Start));
Worker1.Name = "Worker1";
Worker2.Name = "Worker2";
Worker3.Name = "Worker3";
Worker4.Name = "Worker4";
Worker1.Start() ;
Worker2.Start() ;
Worker3.Start() ;
Worker4.Start() ;
Worker4.Join();
Worker3.Join();
Worker2.Join();
Worker1.Join();
Console.WriteLi ne(master.size( ));
master.SetEnume rator();
Updater U1 = new Updater(master, categories[x]);
Updater U2 = new Updater(master, categories[x]);
Updater U3 = new Updater(master, categories[x]);
Thread Updater1 = new Thread(new
ThreadStart(U1. insert));
Thread Updater2 = new Thread(new
ThreadStart(U2. insert));
Thread Updater3 = new Thread(new
ThreadStart(U3. insert));
Updater1.Start( );
Updater2.Start( );
Updater3.Start( );
Updater1.Join() ;
Updater2.Join() ;
Updater3.Join() ;
}
}
}
}

Sep 26 '06 #1
5 3804
Hello, ad***@binindex. net!

aok This is my main. Pretty much it goes through each category and
astarts up 4 worker threads that then ask for groups to gether from.
aMy
aproblem is that when the thread gets done it keeps the mysql
aconnections open so I end up with quite a few at the end. Is there a
adifferent way that I should do this?

Instead of using separate thread you can use ThreadPool class. And several WaitHandle-s to
indicate thread completion.

( http://msdn.microsoft.com/library/de...ogthrepool.asp )

Also it would be more simpler to answer your question if you'll provide source for
WC1.Start method.or at least the part where you work with Db.


[skipped]


--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
Sep 27 '06 #2
ok will post more code when I get home. For now though I have a
managed threadpool class at home that is suppose to be better and
faster than the .net threadpool. Does anyone know if that is correct.

Sep 27 '06 #3

ad***@binindex. net wrote:
ok will post more code when I get home. For now though I have a
managed threadpool class at home that is suppose to be better and
faster than the .net threadpool. Does anyone know if that is correct.
Could you tell us more about this threadpool class? I'm usually
skeptical of anything home grown. If you're wanting something better
than the built-in ThreadPool class then take a look at the concurrency
and coordination runtime (CCR).

http://msdn.microsoft.com/msdnmag/is...s/default.aspx

Brian

Sep 28 '06 #4
I think I got all the regions opened up so all code should be there.

// Stephen Toub
// st***@microsoft .com
//
// ManagedThreadPo ol.cs
// ThreadPool written in 100% managed code. Mimics the core
functionality of
// the System.Threadin g.ThreadPool class.
//
// HISTORY:
// v1.0.1 - Disposes of items remaining in queue when the queue is
emptied
// - Catches errors thrown during execution of delegates
// - Added reset to semaphore, called during empty queue
// - Catches errors when unable to dequeue delegates
// v1.0.0 - Original version
//
// August 27, 2002
// v1.0.1

//
http://www.gotdotnet.com/community/u...agedThreadPool

#region Namespaces
using System;
using System.Threadin g;
using System.Collecti ons;
#endregion

namespace Toub.Threading
{
/// <summary>Implem entation of Dijkstra's PV Semaphore based on the
Monitor class.</summary>
public class Semaphore
{
#region Member Variables
/// <summary>The number of units alloted by this semaphore.</summary>
private int _count;
#endregion

#region Construction
/// <summaryInitial ize the semaphore as a binary
semaphore.</summary>
public Semaphore() : this(1)
{
}

/// <summaryInitial ize the semaphore as a counting
semaphore.</summary>
/// <param name="count">In itial number of threads that can take out
units from this semaphore.</param>
/// <exception cref="ArgumentE xception">Throw s if the count argument
is less than 1.</exception>
public Semaphore(int count)
{
if (count < 0) throw new ArgumentExcepti on("Semaphore must have a
count of at least 0.", "count");
_count = count;
}
#endregion

#region Synchronization Operations
/// <summary>V the semaphore (add 1 unit to it).</summary>
public void AddOne() { V(); }

/// <summary>P the semaphore (take out 1 unit from it).</summary>
public void WaitOne() { P(); }

/// <summary>P the semaphore (take out 1 unit from it).</summary>
public void P()
{
// Lock so we can work in peace. This works because lock is
actually
// built around Monitor.
lock(this)
{
// Wait until a unit becomes available. We need to wait
// in a loop in case someone else wakes up before us. This could
// happen if the Monitor.Pulse statements were changed to
Monitor.PulseAl l
// statements in order to introduce some randomness into the order
// in which threads are woken.
while(_count <= 0) Monitor.Wait(th is, Timeout.Infinit e);
_count--;
}
}

/// <summary>V the semaphore (add 1 unit to it).</summary>
public void V()
{
// Lock so we can work in peace. This works because lock is
actually
// built around Monitor.
lock(this)
{
// Release our hold on the unit of control. Then tell everyone
// waiting on this object that there is a unit available.
_count++;
Monitor.Pulse(t his);
}
}

/// <summary>Rese ts the semaphore to the specified count. Should be
used cautiously.</summary>
public void Reset(int count)
{
lock(this) { _count = count; }
}
#endregion
}

/// <summary>Manage d thread pool.</summary>
public class ManagedThreadPo ol
{
#region Constants
/// <summary>Maximu m number of threads the thread pool has at its
disposal.</summary>
private const int _maxWorkerThrea ds = 15;
#endregion

#region Member Variables
/// <summary>Queu e of all the callbacks waiting to be
executed.</summary>
static Queue _waitingCallbac ks;
/// <summary>
/// Used to signal that a worker thread is needed for processing.
Note that multiple
/// threads may be needed simultaneously and as such we use a
semaphore instead of
/// an auto reset event.
/// </summary>
static Semaphore _workerThreadNe eded;
/// <summary>List of all worker threads at the disposal of the thread
pool.</summary>
static ArrayList _workerThreads;
/// <summary>Numb er of threads currently active.</summary>
static int _inUseThreads;
#endregion

#region Construction
/// <summary>Initia lize the thread pool.</summary>
static ManagedThreadPo ol()
{
// Create our thread stores; we handle synchronization ourself
// as we may run into situtations where multiple operations need to
be atomic.
// We keep track of the threads we've created just for good measure;
not actually
// needed for any core functionality.
_waitingCallbac ks = new Queue();
_workerThreads = new ArrayList();
_inUseThreads = 0;

// Create our "thread needed" event
_workerThreadNe eded = new Semaphore(0);

// Create all of the worker threads
for(int i=0; i<_maxWorkerThr eads; i++)
{
// Create a new thread and add it to the list of threads.
Thread newThread = new Thread(new ThreadStart(Pro cessQueuedItems ));
_workerThreads. Add(newThread);

// Configure the new thread and start it
newThread.Name = "ManagedPoolThr ead #" + i.ToString();
newThread.IsBac kground = true;
newThread.Start ();
}
}
#endregion

#region Public Methods
/// <summary>Queu es a user work item to the thread pool.</summary>
/// <param name="callback" >
/// A WaitCallback representing the delegate to invoke when the
thread in the
/// thread pool picks up the work item.
/// </param>
public static void QueueUserWorkIt em(WaitCallback callback)
{
// Queue the delegate with no state
QueueUserWorkIt em(callback, null);
}

/// <summary>Queu es a user work item to the thread pool.</summary>
/// <param name="callback" >
/// A WaitCallback representing the delegate to invoke when the
thread in the
/// thread pool picks up the work item.
/// </param>
/// <param name="state">
/// The object that is passed to the delegate when serviced from the
thread pool.
/// </param>
public static void QueueUserWorkIt em(WaitCallback callback, object
state)
{
// Create a waiting callback that contains the delegate and its
state.
// Add it to the processing queue, and signal that data is waiting.
WaitingCallback waiting = new WaitingCallback (callback, state);
lock(_waitingCa llbacks.SyncRoo t) {
_waitingCallbac ks.Enqueue(wait ing); }
_workerThreadNe eded.AddOne();
}

/// <summary>Emptie s the work queue of any queued work
items.</summary>
public static void EmptyQueue()
{
lock(_waitingCa llbacks.SyncRoo t)
{
try
{
// Try to dispose of all remaining state
foreach(object obj in _waitingCallbac ks)
{
WaitingCallback callback = (WaitingCallbac k)obj;
if (callback.State is IDisposable)
((IDisposable)c allback.State). Dispose();
}
}
catch
{
// Make sure an error isn't thrown.
}

// Clear all waiting items and reset the number of worker threads
currently needed
// to be 0 (there is nothing for threads to do)
_waitingCallbac ks.Clear();
_workerThreadNe eded.Reset(0);
}
}
#endregion

#region Properties
/// <summary>Gets the number of threads at the disposal of the thread
pool.</summary>
public static int MaxThreads { get { return _maxWorkerThrea ds; } }
/// <summary>Gets the number of currently active threads in the
thread pool.</summary>
public static int ActiveThreads { get { return _inUseThreads; } }
/// <summary>Gets the number of callback delegates currently waiting
in the thread pool.</summary>
public static int WaitingCallback s { get {
lock(_waitingCa llbacks.SyncRoo t) { return _waitingCallbac ks.Count; } }
}
#endregion

#region Thread Processing
/// <summary>A thread worker function that processes items from the
work queue.</summary>
private static void ProcessQueuedIt ems()
{
// Process indefinitely
while(true)
{
// Get the next item in the queue. If there is nothing there, go
to sleep
// for a while until we're woken up when a callback is waiting.
WaitingCallback callback = null;
while (callback == null)
{
// Try to get the next callback available. We need to lock on the

// queue in order to make our count check and retrieval atomic.
lock(_waitingCa llbacks.SyncRoo t)
{
if (_waitingCallba cks.Count 0)
{
try { callback = (WaitingCallbac k)_waitingCallb acks.Dequeue(); }

catch{} // make sure not to fail here
}
}

// If we can't get one, go to sleep.
if (callback == null) _workerThreadNe eded.WaitOne();
}

// We now have a callback. Execute it. Make sure to accurately
// record how many callbacks are currently executing.
try
{
Interlocked.Inc rement(ref _inUseThreads);
callback.Callba ck(callback.Sta te);
}
catch
{
// Make sure we don't throw here. Errors are not our problem.
}
finally
{
Interlocked.Dec rement(ref _inUseThreads);
}
}
}
#endregion

/// <summary>Used to hold a callback delegate and the state for that
delegate.</summary>
private class WaitingCallback
{
#region Member Variables
/// <summary>Callba ck delegate for the callback.</summary>
private WaitCallback _callback;
/// <summary>Stat e with which to call the callback
delegate.</summary>
private object _state;
#endregion

#region Construction
/// <summary>Initia lize the callback holding object.</summary>
/// <param name="callback" >Callback delegate for the
callback.</param>
/// <param name="state">St ate with which to call the callback
delegate.</param>
public WaitingCallback (WaitCallback callback, object state)
{
_callback = callback;
_state = state;
}
#endregion

#region Properties
/// <summary>Gets the callback delegate for the callback.</summary>
public WaitCallback Callback { get { return _callback; } }
/// <summary>Gets the state with which to call the callback
delegate.</summary>
public object State { get { return _state; } }
#endregion
}
}
}

Sep 28 '06 #5

ad***@binindex. net wrote:
I think I got all the regions opened up so all code should be there.
Ah, okay. Yeah, Stephen Toub has another implementation here.

http://msdn.microsoft.com/msdnmag/is...03/NETMatters/

Brian

Sep 29 '06 #6

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

Similar topics

4
2896
by: Gilles Leblanc | last post by:
Hi I have started a small project with PyOpenGL. I am wondering what are the options for a GUI. So far I checked PyUI but it has some problems with 3d rendering outside the Windows platform. I know of WxPython but I don't know if I can create a WxPython window, use gl rendering code in it and then put widgets on top of that...
31
2501
by: AlexeiOst | last post by:
Everywhere in documentation there are recommendations to use threads from thread pooling for relatively short tasks. As I understand, fetching a page or multiple pages (sometimes up to 50 but not tipical) from the Internet and doing some processing on those would be considered to be a big/long task for a thread from a pool. In our app it is possible to break the task into some small ones (thread per fetch and processing thereafter or event...
5
1215
by: Alvin Bruney | last post by:
I dispensed some advice and its bugging me that it may not be 100% accurate. Worker threads should not touch main thread objects. Everybody knows that but if you pass a reference to a form object to a worker thread and you touch that form on the worker thread. All is well. Is that right? Will all really be well? It's a reference to the form object. The worker thread is still modifying the main threads object, reference or not, without...
4
5432
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....
51
54855
by: Hans | last post by:
Hi all, Is there a way that the program that created and started a thread also stops it. (My usage is a time-out). E.g. thread = threading.Thread(target=Loop.testLoop) thread.start() # This thread is expected to finish within a second
9
18027
by: RvGrah | last post by:
I'm completely new to using background threading, though I have downloaded and run through several samples and understood how they worked. My question is: I have an app whose primary form will almost always lead to the user opening a certain child window that's fairly resource intensive to load. Is it possible to load this form in a backgroundworker and then use the Show method and hide method as necessary? Anyone know of
34
2807
by: Creativ | last post by:
Why does Thread class not support IDisposable? It's creating quite some problem. Namely, it can exhaust the resource and you have not control over it.
10
5053
by: Paul E Collins | last post by:
I want to fill an ImageList with bitmaps for a ListView from another thread, because it's a time-consuming process. I expect the ListViewItems' images to "load" one by one, as in a Web browser. I wrote the following code, but the form freezes up while CreateTileBitmaps is running, just as if I'd done it on the main thread. How can I add items to the ImageList without this problem? (Note: I do *not* want to use an owner-draw ListView and...
18
10240
by: =?Utf-8?B?VGhlU2lsdmVySGFtbWVy?= | last post by:
Because C# has no native SSH class, I am using SharpSSH. Sometimes, for reasons I do not know, a Connect call will totally lock up the thread and never return. I am sure it has something to do with weirdness going on with the server I am talking to. Anyhow, this locked up state happens once in a while (maybe once per day) and I can't figure out how to deal with the locked up thread. If I issue a Thread.Abort() the exception never...
9
6980
by: =?Utf-8?B?anAybXNmdA==?= | last post by:
I've got a routine that builds a table using different queries, different SQL Tables, and adding custom fields. It takes a while to run (20 - 45 seconds) so I wrote a thread to handle the table population. Whenever I call the thread, I pass it a structure containing the table and a few other parameters. The table goes in as a reference, but the other items are passed normally.
0
8917
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
8761
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,...
0
9426
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
9142
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
8148
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...
0
4525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2680
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2163
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.