The Microsoft .NET Base Class Library provides several ways to create a thread and start it. Basically the invocation is very similar to every other one providing the same kind of service: create an object representing an execution flow (or more), assign it a delegate representing the execution flow to execute and, eventually, depending on delegate signature, an object as a parameter.
Well, there are two approaches (essentially):
1) Using the System.Threading.Thread class.
Thread curr = new Thread(myfunction); /* In a class, myfunction is a void taking an object */
curr.Start(new Object()); /* Or something else to be downcast */
2) Using the System.Threading.ThreadPool class.
ThreadPool.QueueUserWorkItem(myfunction, new Object()); /* Same philosophy here */
Are there any special reasons why I should use 1) or 2)?
Performance reasons?
Patterns?
What is the best approach?
I have a feeling that the answer is: "Depend by the situation". Could you please list some situations where one approach is better than another?
Starting a new thread can be a very expensive operation. The thread pool reuses threads and thus amortizes the cost. Unless you need a dedicated thread, the thread pool is the recommended way to go. By using a dedicated thread you have more control over thread specific attributes such as priority, culture and so forth. Also, you should not do long running tasks on the thread pool as it will force the pool to spawn additional threads.
In addition to the options you mention .NET 4 offers some great abstractions for concurrency. Check out the Task and Parallel classes as well as all the new PLINQ methods.
The Managed Thread Pool has some very good guidelines on when NOT to use the thread pool.
In my experience, you want to create your own thread when you need a persistent, dedicated, long-running thread. For everything else, use asynchronous delegates or something like QueueUserWorkItem, BackgroundWorker, or the Task-related features of .NET 4.0.
Threads in ThreadPool are background threads;
All threads created and started by a new Thread object are foreground threads.
A background thread does not keep the managed execution environment running.
refer to http://msdn.microsoft.com/en-us/library/h339syd0.aspx for more.
In .NET 4.5.2 they added a new method: HostingEnvironment.QueueBackgroundWorkItem.
This appears to be an alternative to ThreadPool.QueueUserWorkItem. Both behave similarly, but there are some nice benefits to using the new method when working in ASP.NET:
The HostingEnvironment.QueueBackgroundWorkItem method lets you
schedule small background work items. ASP.NET tracks these items and
prevents IIS from abruptly terminating the worker process until all
background work items have completed. This method can't be called
outside an ASP.NET managed app domain.
Using the ThreadPool, you have less control of the threading system. This is a trade off to simplify the process for you. If you have all that you need from the ThreadPool, you should feel free to utilize it. If you need more control of the threads, then you need to of course use the Thread classes.
ThreadPool.QueueUserWorkItem() is basically for fire-and-forget scenarios, when application doesn't depend on whether operations will finish or not.
Use classic threads for fine-grained control.
You should use ThreadPool.QueueUserWorkItem except in cases of:
You require a foreground thread.
You require a thread to have a particular priority.
You have tasks that cause the thread to block for long periods of
time. The thread pool has a maximum number of threads, so a large
number of blocked thread pool threads might prevent tasks from
starting.
You need to place threads into a single-threaded apartment. All
ThreadPool threads are in the multithreaded apartment.
You need to have a stable identity associated with the thread, or to
dedicate a thread to a task.
Reference link.
Related
I'm working on a network-bound application, which is supposed to have a lot (hundreds, may be thousands) of parallel processes.
I'm looking for the best way to implement it.
When I tried setting
ThreadPool.SetMaxThreads(int.MaxValue, int.MaxValue);
and than creating 1000 threads and making those do stuff in parallel, application's execution became really jumpy.
I've heard somewhere that delegate.BeginInvoke is somehow better that new Thread(...), so I've tried it, and than opened the app in debugger, and what I've seen are parallel threads.
If I have to create lots and lots of threads, what is the best way to ensure that the application is going to run smoothly?
Have you tried the new await / async pattern in C# 5 / .NET 4.5?
I haven't got sources to hand about how this operates under the hood, but one of the most common use-cases of this new feature is waiting for IO bound stuff.
Threads are not lightweight objects. They are expensive to create and context switch to/from; hence the reason for the Thread Pool (pre-created and recycled). Most common solutions that involve networking or other IO ports utilise lower-level IO Completion Ports (there is a managed library here) to "wait" on a port, but where the thread can continue executing as normal.
BeginInvoke will utilise a Thread Pool thread, so it will be better than creating your own only if a thread is available. This approach, if used too heavily, can immediately result in thread starvation.
Setting such a high thread pool count is not going to work in the long run as threads are too heavy for what it appears you want to do.
Axum, a former Microsoft Research language, used to achieve massive parallelism that would have been suitable for this task. It operated similarly to Stackless Python or Erlang. Lots of concepts from Axum made their way into the parallelism drive into C# 5 and .NET 4.5.
Setting the ThreadPool.SetMaxThreads will only affect how many threads the thread pool has, and it won't make a difference regarding threads you create yourself with new Thread().
Go async (model, not keyword) as suggested by many.
You should follow the advice mentioned in the other answers and comments. As fsimonazzi says, creating new threads directly has nothing to do with the ThreadPool. For a quick test lower the max worker and completionPort threads and use the ThreadPool.QueueUserWorkItem method. The ThreadPool will decide what your system can handle, queue your tasks and resuse threads whenever it can.
If your tasks are not compute-bound then you should also utilize asynchronous I/O. You do not your worker threads to wait for I/O completion. You need those worker threads to return to the pool as quickly as possible and not block on I/O requests.
So far during my experience in Windows Phone 7 application development I notices there are different ways to runs an action in an asynchronous thread.
System.Threading.Thread
System.ComponentModel.BackgroundWorker
System.Threading.ThreadPool.QueueUserWorkItem()
I couldn't see any tangible difference between these methods (other than that the first two are more traceable).
Is there any thing you guys consider before using any of these methods? Which one would you prefer and why?
The question is kinda answered but the answers are a little short on detail (IMO).
Lets take each in turn.
System.Threading.Thread
All the threads (in the CLR anyway) are ultimately represented by this class. However you probably included this to query when we might want to create an instance ourselves.
The answer is rarely. Ordinarily the day-to-day workhorse for dispatching background tasks is the Threadpool. However there are some circumstances where we would want to create our own thread. Typically such a thread would live for most of the app runtime. It would spend most of its life in blocked on some wait handle. Occasionally we signal this handle and it comes alive to do something important but then it goes back to sleep. We don't use a Threadpool work item for this because we do not countenance the idea that it may queue up behind a large set of outstanding tasks some of which may themselves (perhaps inadverently) be blocked on some other wait.
System.ComponentModel.BackgroundWorker
This is friendly class wrapper around the a ThreadPool work item. This class only to the UI oriented developer who occasionally needs to use a background thread. Its events being dispatched on the UI thread makes it easy to consume.
System.Threading.ThreadPool.QueueUserWorkItem
This the day-to-day workhorse when you have some work you want doing on a background thread. This eliminates the expense of allocating and deallocating individual threads to perform some task. It limits the number of thread instances to prevent too much of the available resources being gobbled up by too many operations try to run in parallel.
The QueueUserWorkItem is my prefered option for invoking background operations.
It arguably depends on what you are trying to do, you have listed 3 very different threading models.
Basic threading
Designed for applications with a seperate UI thread.
Managed thread pool
Have you read MSDN etc...
http://www.albahari.com/threadin
Http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx
You don't state "what for", but
Basic Thread - quite expensive, not for small jobs
Backgroundworker - mostly for UI + Progressbar work
ThreadPool - for small independent jobs
I think the TPL is not supported in SL, which is a pity.
The background worker tends to be better to use when your UI needs to be update as your thread progresses because it handles invoking the call back functions (such as the OnProgress callback) on the UI thread rather than the background thread. The other two don't do this work. It is up to you to do it.
I know that the CLR gives each AppDomain ThreadPool time slice to work , yet i wanted to know if by creating a new thread like so Thread t = new Thread(...);
Is it managed by the CLR or by the AppDomin ThreadPool ?
Thread t = new Thread(); will not be managed by the ThreadPool. But it is an abstraction provided by the CLR on the Operating System threads. ThreadPool is an addtional abstraction which facilitates reusing threads and sharing thread resources.
Here is an excellent resource on threads in .NET: http://www.albahari.com/threading/
If you're using .NET 4.0 consider using TPL.
When you create threads with the Thread class, you are in control. You create them as you need them, and you define whether they are background or foreground (keeps the calling process alive), you set their Priority, you start and stop them.
With ThreadPool or Task (which use the ThreadPool behind the scenes) you let the ThreadPool class manage the creation of threads, and maximizes reusability of threads, which saves you the time needed to create a new thread. One thing to notice is that unlike the Thread default, threads created by the ThreadPool don't keep the calling process alive.
A huge advantage of using the ThreadPool is that you can have a small number of threads handle lots of tasks. Conversely, given that the pool doesn't kill threads (because it's designed for reusability), if you had a bunch of threads created by the ThreadPool, but later the number of items shrinks, the ThreadPool idles a lot, wasting resources.
When you create new threads they are not managed by the thread pool.
If you create a thread manually then you control its life time, this is independent from the Thread pool.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Advantage of using Thread.Start vs QueueUserWorkItem
If i want to execute a method through a thread ,so i usually use System.Thread like this
Thread th = new Thread(Test_Progress);
th.Start();
but my colleague told me that using the ThreadPool.QueueUserWorkItem like the following is better
ThreadPool.QueueUserWorkItem(new WaitCallback(Test_Progress),(object)true );
So is there any difference like performance and how the it's handled ??
Threads are expensive objects to create, using the threadpool is a better way of performing quick work on a separate thread without having to deal with the full cost of creating a new thread.
Additionally, you want to make sure you're not performing a very long executing operation on a pool thread, because you can exhaust the pool's limited number of threads.
You should read the MSDN documentation about the threadpool located here: http://msdn.microsoft.com/en-us/library/0ka9477y.aspx
It will explain some things to keep in mind when trying to decide what to use.
ThreadPool is pool (collection) of threads and using it will pick a thread from this pool and execute your method inside that thread where as Thread object created new Thread.
This is a general concept around Object pooling i.e when in your application you need to use several objects one option is to create a pool of those object and pick object from this pool use it and then put back it in pool, this is done in those cases where the object creation is expensive and this also leads to better scalability. In case of threads if your application creates many threads then it will crawl very slowly because of context switching hence it is prefered to use Thread pool. Another example of same concept is SQL Connection pool.
If you have lots of short running tasks use a thread pool. If you have only few and long running tasks, usage of threads is better.
Usage of threads enables you to have more fine control over your tasks, in contrast usage of tread pool can make things easier.
my Question is :
I am trying to work with multi threading TECHNIC
so I used threadPool but what I want is the following
I want to identify the size of the ThreadPool when the program is launching
when I have Data to manage , I will take a thread from The ThreadPool to work with this Item,
as I have read you can define items in threadPool as you want but each thread will Run Automaticly I want to to have control over the thread to determine when the thread should run
If no Data The thread should wait(or stop) when I have a new Data(it's like a request)
one of the threads will run ..... thanks
When using the ThreadPool you will typically queue a request to the pool with some (optional) input data, which will cause the pool to pick an available thread and run the process. When that is done, the thread is returned to the pool, and will be available for another request. You usually do not need to bother about managing the threads, but can simply queue a work item whenever needed:
DataToWorkWith dataItem = GetDataToWorkWith();
if (dataItem != null)
{
ThreadPool.QueueUserWorkItem(MyProcessingMethod, dataItem);
}
// somewhere else in the class
private void MyProcessingMethod(object dataItem)
{
// work with the dataItem; this will run on a threadpool thread, if
// invoked through the thread pool
}
So, all you would need to do is set up some process figuring out if there is data to work with, queue the requests in the ThreadPool and let it do its job.
Here's a short summary on the C# ThreadPool Usage. Here's the MSDN How To: Use a ThreadPool. And here's the ThreadPool reference.
In particular, you can get the available threads using GetAvailableThreads. You can also control the min and max number of threads in the thread pool by using SetMinThreads and SetMaxThreads.
In general though, I would advise against messing with the numbers of threads, unless you know exactly what you are doing. The thread pool is shared by you and the CLR components, so by changing the number of threads you can affect the CLR behavior. For more details, read the Remarks section in the ThreadPool class documentation.
You don't typically manually manage threads from the ThreadPool. The recommended usage is to queue a delegate as Fredrik exemplified, and let the ThreadPool manage the thread. With this convention, if there is no data, you shouldn't queue any work. When data becomes available, you can queue the work. If you're looking for a way to run a background process, when your application starts, you can create a Timer and add it to the application's state, or you can define a static class that manages a Timer and touch that class on application start.