diff --git a/Docs/Mono.jpg b/Docs/Mono.jpg new file mode 100644 index 0000000..e59723c Binary files /dev/null and b/Docs/Mono.jpg differ diff --git a/Docs/Silverlight.jpg b/Docs/Silverlight.jpg new file mode 100644 index 0000000..2a3c8a3 Binary files /dev/null and b/Docs/Silverlight.jpg differ diff --git a/Docs/SmartThreadPool.JPG b/Docs/SmartThreadPool.JPG index 721e5ec..d724617 100644 Binary files a/Docs/SmartThreadPool.JPG and b/Docs/SmartThreadPool.JPG differ diff --git a/Docs/SmartThreadPool.html b/Docs/SmartThreadPool.html index 4a21efd..163fbc9 100644 --- a/Docs/SmartThreadPool.html +++ b/Docs/SmartThreadPool.html @@ -1,11 +1,13 @@ -

+ + +

See the history section at the bottom for changes.

Basic usage

-

This is a Thread Pool, if you got here you probably you know what you +

This is a Thread Pool, if you got here you probably know what you need. If you want to understand the features and know how it works keep reading the sections below. If you just want to use it, here is a quick usage snippet. See examples for advanced usage.

-
    
+
    
    // Create an instance of the Smart Thread Pool
    SmartThreadPool smartThreadPool = new SmartThreadPool();
 
@@ -16,23 +18,28 @@
 

Introduction

Smart Thread Pool is a thread pool written in C#. The implementation was first based on Stephan Toub's thread pool with some extra features, but now it is far beyond the original. Here is a list of the thread pool features:

Why do you need a thread pool?

@@ -41,69 +48,78 @@

Smart Thread Pool Features

When I wrote my application, I discovered that I needed a thread pool with the following features:

    -
  • The thread pool should implement the QueueUserWorkItem() method to comply with the .NET ThreadPool. -
  • The thread pool should be instantiated. (No static methods.) So, the threads in the pool are used only for one purpose. -
  • The number of threads in the pool should be dynamic with lower and upper limits.
+
  • The thread pool should implement the QueueUserWorkItem() method to comply with the .NET ThreadPool. +
  • The thread pool should be instantiated. (No static methods.) So, the threads in the pool are used only for one purpose. +
  • The number of threads in the pool should be dynamic with lower and upper limits.
  • After I published the smart thread pool here, I found out that more features were required and some features had to change. So, the following is an updated list of the implemented features:

      -
    1. The thread pool is instantiable. -
    2. The number of threads dynamically changes. -
    3. Work items return a value. -
    4. The caller can wait for multiple work items to complete. -
    5. A work item can be cancelled. -
    6. The caller thread's context is used when the work item is executed (limited). -
    7. Usage of minimum number of Win32 event handles, so the handle count of the application won't explode.
    +
  • The thread pool is instantiable. +
  • The number of threads dynamically changes. +
  • Work items return a value. +
  • The caller can wait for multiple work items to complete. +
  • A work item can be cancelled. +
  • The caller thread's context is used when the work item is executed (limited). +
  • Usage of minimum number of Win32 event handles, so the handle count of the application won't explode.
  • Because of features 3 and 5, the thread pool no longer complies to the .NET ThreadPool, and so I could add more features.

    See the additional features section below for the new features added in this version.

    Additional features added in December 2004

    1. Every work item can have a PostExecute callback. This is a method that will be called right after the work item execution has been completed. -
    2. The user can choose to automatically dispose off the state object that accompanies the work item. -
    3. The user can wait for the Smart Thread Pool to become idle. -
    4. The exception handling is changed, so if a work item throws an exception, it is re-thrown at GetResult(), rather than firing an UnhandledException event. Note that PostExecute exceptions are always ignored.
    +
  • The user can choose to automatically dispose off the state object that accompanies the work item. +
  • The user can wait for the Smart Thread Pool to become idle. +
  • The exception handling is changed, so if a work item throws an exception, it is re-thrown at GetResult(), rather than firing an UnhandledException event. Note that PostExecute exceptions are always ignored.
  • New features added in January 2006

    1. Work items have priority. -
    2. The caller thread's HTTP context can be used when the work item is executed (improves 6.). -
    3. Work items group. -
    4. The caller can create thread pools and work item groups in suspended state. -
    5. Threads have priority.
    +
  • The caller thread's HTTP context can be used when the work item is executed (improves 6.). +
  • Work items group. +
  • The caller can create thread pools and work item groups in suspended state. +
  • Threads have priority.
  • New features added in May 2008

      -
    1. Enabled the change of the MaxThreads/MinThreads/Concurrency at run time.
    2. -
    3. Improved the Cancel behavior. (See section 5)
    4. -
    5. Added callbacks for initialization and termination of threads.
    6. +
    7. Enabled the change of the MaxThreads/MinThreads/Concurrency at run time.
    8. +
    9. Improved the Cancel behavior. (See section 5)
    10. +
    11. Added callbacks for initialization and termination of threads.
    12. Added support for WinCE (limited)
    13. Added IsIdle flag to the SmartThreadPool and to the IWorkItemsGroup
    14. Added support for Action<T> and Func<T> (strong typed work items)
    +

    + New features added in April 2009

    +
      +
    1. Added support for Silverlight.
    2. +
    3. Added support for Mono.
    4. +
    5. Added internal performance coutnters (for WindowsCE, Silverlight, and Mono).
    6. +
    7. Added new methods: Join, Choice, and Pipe.
    8. +
    +

    What about the .NET ThreadPool?

    -

    The Windows system provides one .NET ThreadPool for each process. The .NET ThreadPool can contain up to 25 (by default) threads per processor. It is also stated that the operations in .NET ThreadPool should be quick to avoid suspension of the work of others who use the .NET ThreadPool. Note that several AppDomains in the same process share the same .NET ThreadPool. If you want a thread to work for a long period of time, then the .NET ThreadPool is not a good choice for you (unless you know what you are doing). Note that each asynchronous method call from the .NET Framework that begins with "Begin…" (e.g., BeginInvoke, BeginSend, BeginReceive, etc.) uses the .NET ThreadPool to run its callback. Also note that the .NET ThreadPool +

    The Windows system provides one .NET ThreadPool for each process. The .NET ThreadPool can contain up to 25 (by default) threads per processor. It is also stated that the operations in .NET ThreadPool should be quick to avoid suspension of the work of others who use the .NET ThreadPool. Note that several AppDomains in the same process share the same .NET ThreadPool. If you want a thread to work for a long period of time, then the .NET ThreadPool is not a good choice for you (unless you know what you are doing). Note that each asynchronous method call from the .NET Framework that begins with "Begin…" (e.g., BeginInvoke, BeginSend, BeginReceive, etc.) uses the .NET ThreadPool to run its callback. Also note that the .NET ThreadPool doesn't support calls to COM with single threaded apartment (STA), since the ThreadPool threads are MTA by design.

    -

    This thread pool doesn't comply with the requirements 1, 5, 6, 8, 9, 10, 12-22.

    +

    This thread pool doesn't comply with the requirements 1, 5, 6, 8, 9, 10, 12-25.

    Note that the requirements 3 and 4 are implemented in .NET ThreadPool with delegates.

    What about Stephen Toub's thread pool?

    -

    Toub's thread pool is a better choice than the .NET ThreadPool, since a thread from his pool can be used for a longer period of time, without affecting the asynchronous method calls. Toub's thread pool uses static methods; hence you cannot instantiate more than one thread pool. However, this limitation applies per AppDomain rather than the whole process. The main disadvantage of Toub's thread pool over the .NET TheradPool is that Toub creates all the threads in the pool at the initialization point, while the .NET ThreadPool creates threads on the fly.

    -

    This thread pool doesn't comply with the requirements 1, 2, 3, 4, 5, 6, 8-22.

    +

    Toub's thread pool is a better choice than the .NET ThreadPool, since a thread from his pool can be used for a longer period of time, without affecting the asynchronous method calls. Toub's thread pool uses static methods; hence you cannot instantiate more than one thread pool. However, this limitation applies per AppDomain rather than the whole process. The main disadvantage of Toub's thread pool over the .NET TheradPool is that Toub creates all the threads in the pool at the initialization point, while the .NET ThreadPool creates threads on the fly.

    +

    This thread pool doesn't comply with the requirements 1, 2, 3, 4, 5, 6, 8-25.

    The Smart Thread Pool design and features

    As I mentioned before, the Smart Thread Pool is based on Toub's thread pool implementation. However, since I have expanded its features, the code is no longer similar to the original one.

    Features implementation:

      -
    1. The thread pool is instantiated. +
    2. The thread pool is instantiable.

      The reason I need an instantiable thread pool is because I have different needs. I have work items that take a long time to execute and I have work items that take very short time to execute. Executing the same type of work items on the same thread pool may cause some serious performance or response problems.

      -

      To implement this feature, I just copied Toub's implementation and removed the static keyword from the methods. That's the easy part of it.

      -
    3. The number of threads dynamically changes. +

      To implement this feature, I just copied Toub's implementation and removed the static keyword from the methods. That's the easy part of it.

      +
    4. The number of threads dynamically changes.

      The number of threads dynamically changes according to the workload on the threads in the pool, with lower and upper constraints for the number of threads in the pool. This feature is needed so we won't have redundant threads in the application.

      This feature is a real issue and is the core of the Smart Thread Pool. How do you know when to add a new thread and when to remove it?

      I decided to add a new thread every time a new work item is queued and all the threads in the pool are busy. The formula for adding a new thread can be summarized to:

      (InUseThreads + WaitingCallbacks) > WorkerThreads
      -

      where WorkerThreads is the current number of threads in the pool, InUseThreads is the number of threads in the pool that are currently working on a work item, and WaitingCallbacks is the number of waiting work items. (Thanks to jrshute for the comment.)

      -

      The SmartThreadPool.Enqueue() method looks like this:

      private void Enqueue(WorkItem workItem) 
      +

      where WorkerThreads is the current number of threads in the pool, InUseThreads is the number of threads in the pool that are currently working on a work item, and WaitingCallbacks is the number of waiting work items. (Thanks to jrshute for the comment.)

      +

      The SmartThreadPool.Enqueue() method looks like this:

      private void Enqueue(WorkItem workItem) 
       { 
           // Make sure the workItem is not null 
           Debug.Assert(null != workItem); 
      @@ -127,113 +143,113 @@
       

      The thread pool contains four threads. Let's name them A, B, C, and D. Every second a new work item arrives, and it takes less than one second and a half to handle each work item:

      - + +

      Work item arrival time (sec)

      +

      Work item work duration (sec)

      +

      Threads queue state

      - +

      The thread that will execute the arrived work item

      + +

      00:00:00

      +

      1.5

      +

      A, B, C, D

      - +

      A

      + +

      00:00:01

      +

      1.5

      +

      B, C, D

      - +

      B

      + +

      00:00:02

      +

      1.5

      +

      C, D, A

      - +

      C

      + +

      00:00:03

      +

      1.5

      +

      D, A, B

      -

      Work item arrival time (sec)

      -

      Work item work duration (sec)

      -

      Threads queue state

      -

      The thread that will execute the arrived work item

      -

      00:00:00

      -

      1.5

      -

      A, B, C, D

      -

      A

      -

      00:00:01

      -

      1.5

      -

      B, C, D

      -

      B

      -

      00:00:02

      -

      1.5

      -

      C, D, A

      -

      C

      -

      00:00:03

      -

      1.5

      -

      D, A, B

      -

      D

      +

      D

      In this scenario, all the four threads are used, although two threads could handle all the work items.

      The solution is to implement the waiters queue as a stack. In this implementation, the last arrived waiter for a work item gets it first (stack). This way, a thread that just finished its work on a work item waits as the first waiter in the queue of waiters.

      The previous scenario will look like this with the new implementation:

      - + +

      Work item arrival time (sec)

      +

      Work item work duration (sec)

      +

      Threads queue state

      - +

      The thread that will execute the arrived work item

      + +

      00:00:00

      +

      1.5

      +

      A, B, C, D

      - +

      A

      + +

      00:00:01

      +

      1.5

      +

      B, C, D

      - +

      B

      + +

      00:00:02

      +

      1.5

      +

      A, C, D

      - +

      A

      + +

      00:00:03

      +

      1.5

      +

      B, C, D

      -

      Work item arrival time (sec)

      -

      Work item work duration (sec)

      -

      Threads queue state

      -

      The thread that will execute the arrived work item

      -

      00:00:00

      -

      1.5

      -

      A, B, C, D

      -

      A

      -

      00:00:01

      -

      1.5

      -

      B, C, D

      -

      B

      -

      00:00:02

      -

      1.5

      -

      A, C, D

      -

      A

      -

      00:00:03

      -

      1.5

      -

      B, C, D

      -

      B

      +

      B

      Threads A and B handle all the work items, since they get back to the front of the waiters queue after they have finished. Threads C and D are starved, and if the same work items are going to arrive for a long time, then the threads C and D will have to quit.

      The thread pool doesn't implement a load balancing mechanism, since all the threads run on the same machine and take the same CPUs. Note that if you have many threads in the pool, then you will prefer minimum number of threads to do the job, since each context switch of the threads may result in paging of the threads' stacks. Less working threads means less paging of the threads' stacks.

      The work items queue implementation causes threads to starve, and the starved threads quit. This solves the scenario I mentioned earlier without using any extra thread.

      The second feature also states that there should be a lower limit to the number of threads in the pool. To implement this feature, every thread that gets a timeout, because it doesn't get any work items, checks whatever it can to quit. The Smart Thread Pool allows the thread to quit only if the current number of threads is above the lower limit. If the number of threads in the pool is below or equal to the lower limit, then the thread stays alive.

    5. Work items return a value. (This feature is enhanced)

      This feature is very useful in cases you want to know the result of a work item.

      -

      The .NET ThreadPool supports this feature via delegates. Each time you create a delegate you get for free BeginInvoke() and EndInvoke() methods. The BeginInvoke() queues the method and its parameters on the .NET ThreadPool and the EndInvoke() returns the result of the method. The delegate class is sealed so I couldn't override the BeginInvoke() and EndInvoke() methods. I took a different approach to implement this.

      +

      The .NET ThreadPool supports this feature via delegates. Each time you create a delegate you get for free BeginInvoke() and EndInvoke() methods. The BeginInvoke() queues the method and its parameters on the .NET ThreadPool and the EndInvoke() returns the result of the method. The delegate class is sealed so I couldn't override the BeginInvoke() and EndInvoke() methods. I took a different approach to implement this.

      First, the work item callback delegate can return a value:

      -
      public delegate object WorkItemCallback(object state);
      +
      public delegate object WorkItemCallback(object state);
      Or in its enhanced form the callback can be any of the following forms: -
      public delegate void Action(); 
      +
      public delegate void Action(); 
       public delegate void Action<T>(T arg); 
       public delegate void Action<T1, T2>(T1 arg1, T2 arg2); 
       public delegate void Action<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3); 
      @@ -245,10 +261,10 @@ public delegate TResult Func<T1, T2>(T1 arg1, T2 arg2);
       public delegate TResult Func<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3); 
       public delegate TResult Func<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4); 
       
      -(Note that the above delegates are defined in .NET 3.5. In .NET 2.0 & 3.0 only public delegate void Action<T>(T arg) is defined)
      -Second, the SmartThreadPool.QueueWorkItem() method returns a reference to an object that implements the - IWorkItemResult<TResult> interface. The caller can use this object to get the result of the work item. The interface is similar to the IAsyncResult interface: -
      public interface IWorkItemResult<TResult>
      +(Note that the above delegates are defined in .NET 3.5. In .NET 2.0 & 3.0 only public delegate void Action<T>(T arg) is defined)
      +Second, the SmartThreadPool.QueueWorkItem() method returns a reference to an object that implements the + IWorkItemResult<TResult> interface. The caller can use this object to get the result of the work item. The interface is similar to the IAsyncResult interface: +
      public interface IWorkItemResult<TResult>
       { 
           /// Get the result of the work item. 
           /// If the work item didn't run yet then the caller waits
      @@ -308,88 +324,88 @@ Second, the SmartThreadPool.QueueWorkItem() method returns a refere
       

      - If the work item callback is  object WorkItemCallback(object state) - then IWorkItemResult is returned and GetResult() returns object. Same as in previous versions

      + If the work item callback is  object WorkItemCallback(object state) + then IWorkItemResult is returned and GetResult() returns object. Same as in previous versions

      - If the work item callback is one of the Func<...> methods I mentioned above, the result of the QueueWorkItem is IWorkItemResult<TResult>. So the result of the work item is strongly typed. + If the work item callback is one of the Func<...> methods I mentioned above, the result of the QueueWorkItem is IWorkItemResult<TResult>. So the result of the work item is strongly typed.

      - If the work item callback is one of the Action<...> methods I mentioned above, the result of the QueueWorkItem is IWorkItemResult and GetResult() always returns null. + If the work item callback is one of the Action<...> methods I mentioned above, the result of the QueueWorkItem is IWorkItemResult and GetResult() always returns null.

      - If the work item callback is Action<...> or Func<...> and - WIGStartInfo.FillStateWithArgs is set to true then the State of the - IWorkItemResult is initialized with object [] that contains the work item - arguments. Otherwise the State is null.

      + If the work item callback is Action<...> or Func<...> and + WIGStartInfo.FillStateWithArgs is set to true then the State of the + IWorkItemResult is initialized with object [] that contains the work item + arguments. Otherwise the State is null.

      The code examples in the section below shows some snippets of how to use it.

      -

      To get the result of the work item, use the Result property or the GetResult() method. This method has several overloads. In the interface above, I have written only some of them. The other overloads use less parameters by giving default values. The GetResult() returns the result of the work item callback. If the work item hasn't completed then the caller waits until one of the following occurs:

      +

      To get the result of the work item, use the Result property or the GetResult() method. This method has several overloads. In the interface above, I have written only some of them. The other overloads use less parameters by giving default values. The GetResult() returns the result of the work item callback. If the work item hasn't completed then the caller waits until one of the following occurs:

      - - - - - - - - - - - - - - - - - -
      GetResult() return reasonGetResult() return value
      The work item has been executed and completed.The result of the work item.
      The work item has been canceled.Throws WorkItemCancelException.
      The timeout expired.Throws WorkItemTimeoutException.
      The cancelWaitHandle is signaled.Throws WorkItemTimeoutException.
      The work item threw an exception.Throws WorkItemResultException with the work item's exception as the inner exception.
      + +GetResult() return reason +GetResult() return value + +The work item has been executed and completed. +The result of the work item. + +The work item has been canceled. +Throws WorkItemCancelException. + +The timeout expired. +Throws WorkItemTimeoutException. + +The cancelWaitHandle is signaled. +Throws WorkItemTimeoutException. + +The work item threw an exception. +Throws WorkItemResultException with the work item's exception as the inner exception.

      There are two ways to wait for a single work item to complete:

        -
      1. The following function uses the GetResult() method which blocks the caller until the result is available:
        private void WaitForResult1(IWorkItemResult wir)
        +
      2. The following function uses the GetResult() method which blocks the caller until the result is available:
        private void WaitForResult1(IWorkItemResult wir)
         {
             wir.GetResult();
         }
        -
      3. The following function is not recommended, because it uses a busy wait loop. You can use it if you know what you are doing:
        private void WaitForResult2(IWorkItemResult wir)
        +
      4. The following function is not recommended, because it uses a busy wait loop. You can use it if you know what you are doing:
        private void WaitForResult2(IWorkItemResult wir)
         {
             while(!wir.IsCompleted)
             {
                 Thread.Sleep(100);
             }
        -}
      -
    6. The caller can wait for multiple work items to complete. -

      This feature is very useful if you want to run several work items at once and then wait for all of them to complete. The SmartThreadPool class has two static methods for this: WaitAny() and WaitAll() (they have several overloads). Their signature is similar to the WaitHandle equivalent methods except that in the SmartThreadPool case, it gets an array of  -IWaitableResult (the IWorkItemResult interface inherits from IWaitableResult) objects instead of WaitHandle objects.

      -

      The following snippets show how to wait for several work item results at once. Assume wir1 and wir2 are of type IWorkItemResult. You can wait for both work items to complete:

      // Wait for both work items complete 
      +}
    +
  • The caller can wait for multiple work items to complete. +

    This feature is very useful if you want to run several work items at once and then wait for all of them to complete. The SmartThreadPool class has two static methods for this: WaitAny() and WaitAll() (they have several overloads). Their signature is similar to the WaitHandle equivalent methods except that in the SmartThreadPool case, it gets an array of  +IWaitableResult (the IWorkItemResult interface inherits from IWaitableResult) objects instead of WaitHandle objects.

    +

    The following snippets show how to wait for several work item results at once. Assume wir1 and wir2 are of type IWorkItemResult. You can wait for both work items to complete:

    // Wait for both work items complete 
     SmartThreadPool.WaitAll(new IWaitableResult[] { wir1, wir2});
    -

    Or, for any of the work items to complete:

    // Wait for at least one of the work items complete 
    +

    Or, for any of the work items to complete:

    // Wait for at least one of the work items complete 
     SmartThreadPool.WaitAny(new IWaitableResult[] { wir1, wir2});
    -

    The WaitAll() and WaitAny() methods are overloaded, so you can specify timeout, exit context, and cancelWaitHandle (just like in the GetResult() method mentioned earlier).

    -

    Note that in order to use WaitAny() and WaitAll(), you need to work in MTA, because internally I use WaitHandle.WaitAny() and WaitHandle.WaitAll() which requires it. If you don't do that, the methods will throw an exception to remind you.

    -

    Also note that Windows supports WaitAny() of up to 64 handles. The WaitAll() is more flexible and I re-implemented it so it is not limited to 64 handles.

    +

    The WaitAll() and WaitAny() methods are overloaded, so you can specify timeout, exit context, and cancelWaitHandle (just like in the GetResult() method mentioned earlier).

    +

    Note that in order to use WaitAny() and WaitAll(), you need to work in MTA, because internally I use WaitHandle.WaitAny() and WaitHandle.WaitAll() which requires it. If you don't do that, the methods will throw an exception to remind you.

    +

    Also note that Windows supports WaitAny() of up to 64 handles. The WaitAll() is more flexible and I re-implemented it so it is not limited to 64 handles.

    See in the examples section below the code snippets for WaitAll and WaitAny.

    -
  • A work item can be cancelled. (This feature is enhanced) +
  • A work item can be cancelled. (This feature is enhanced)

     This feature enables to cancel work items.

    There are several options to cancel work items. To cancel a single work item call - to IWorkItemResult.Cancel(). To cancel more than one call to IWorkItemsGroup.Cancel() - or SmartThreadPool.Cancel(). All cancels works in O(1). + to IWorkItemResult.Cancel(). To cancel more than one call to IWorkItemsGroup.Cancel() + or SmartThreadPool.Cancel(). All cancels works in O(1).

    There is no guarantee that a work item will be cancelled, it depends on the state of the work item when the cancel is called and the cooperation of the work item. (Note the work item's state I mention here has nothing to do with the state object - argument provided in the QueueWorkItem).

    + argument provided in the QueueWorkItem).

    - These are the possible states of a work item: (defined in the WorkItemState enum)
    + These are the possible states of a work item: (defined in the WorkItemState enum)

      -
    • Queued – The work item is waiting in a queue to be executed.
    • -
    • In Progress – A thread from the pool is executing the work item.
    • -
    • Completed – The work item execution has been completed.
    • -
    • Cancelled – The work item has been cancelled.
    • +
    • Queued – The work item is waiting in a queue to be executed.
    • +
    • In Progress – A thread from the pool is executing the work item.
    • +
    • Completed – The work item execution has been completed.
    • +
    • Cancelled – The work item has been cancelled.

    The cancel behavior depends on the state of the work item.

    @@ -440,21 +456,21 @@ SmartThreadPool.WaitAny(new IWaitableResult[] { wir1, wir2});
  • - Cancelled work item throws WorkItemCancelException when their GetResult() methods + Cancelled work item throws WorkItemCancelException when their GetResult() methods is called.

    - The behavior of the Cancel() when the work item is in Completed or Cancelled states + The behavior of the Cancel() when the work item is in Completed or Cancelled states is straight forward so I won't get into details. A queued work item is marked as cancelled and is discarded once a thread from the pool dequeues it.

    If the work item is in the In Progress state then the behavior depends on the value - of abortExecution in the Cancel call. When the abortExecution is true, a Thread.Abort() - will be called upon the executing thread. When the abortExecution is false, the - work item method is responsible to sample the SmartThreadPool.IsWorkItemCanceled + of abortExecution in the Cancel call. When the abortExecution is true, a Thread.Abort() + will be called upon the executing thread. When the abortExecution is false, the + work item method is responsible to sample the SmartThreadPool.IsWorkItemCanceled static method and quit. Note that in both cases the work item is cancelled and throws - the WorkItemCancelException on GetResult().

    + the WorkItemCancelException on GetResult().

    Here is an example of a cooperative work item:

    @@ -475,29 +491,29 @@ Here is an example of a cooperative work item: } }
  • -
  • The caller thread's context is used when the work item is executed (limited). -

    This feature should be elementary, but it is not so simple to implement. In order to pass the thread's context, the caller thread's CompressedStack should be passed. This is impossible since Microsoft blocks this option with security. Other parts of the thread's context can be passed. These include:

    +
  • The caller thread's context is used when the work item is executed (limited). +

    This feature should be elementary, but it is not so simple to implement. In order to pass the thread's context, the caller thread's CompressedStack should be passed. This is impossible since Microsoft blocks this option with security. Other parts of the thread's context can be passed. These include:

    -

    The first three belong to the System.Threading.Thread class (static or instance) and are get/set properties. However, the last one is a read only property. In order to set it, I used reflection, which slows down the application. If you need this context, just remove the comments from the code.

    -

    To simplify the operation of capturing the context and then applying it later, I wrote a special class that is used internally and does all that stuff. The class is called CallerThreadContext and it is used internally. When Microsoft unblocks the protection on the CompressedStack, I will add it there.

    -

    The caller thread's context is stored when the work item is created, within the EnqueueWorkItem() method. Each time a thread from the pool executes a work item, the thread's context changes in the following order:

    +
  • CurrentCulture - The culture of the thread. +
  • CurrentUICulture - The culture used by the resource manager to look up culture-specific resources at run time. +
  • CurrentPrincipal - The current principal (for role-based security). +
  • CurrentContext - The current context in which the thread is executing. (Used in remoting.)
  • +

    The first three belong to the System.Threading.Thread class (static or instance) and are get/set properties. However, the last one is a read only property. In order to set it, I used reflection, which slows down the application. If you need this context, just remove the comments from the code.

    +

    To simplify the operation of capturing the context and then applying it later, I wrote a special class that is used internally and does all that stuff. The class is called CallerThreadContext and it is used internally. When Microsoft unblocks the protection on the CompressedStack, I will add it there.

    +

    The caller thread's context is stored when the work item is created, within the EnqueueWorkItem() method. Each time a thread from the pool executes a work item, the thread's context changes in the following order:

      -
    1. The current thread context is captured. -
    2. The caller thread context is applied. -
    3. The work item is executed. -
    4. The current old thread context is restored.
    +
  • The current thread context is captured. +
  • The caller thread context is applied. +
  • The work item is executed. +
  • The current old thread context is restored.
  • -
  • Usage of minimum number of Win32 event handles, so the handle count of the application won't explode. -

    The seventh feature is a result of Kevin's comment on the earlier version of Smart Thread Pool. It seemed that the test application consumed a lot of handles (Handle Count in the Task Manager) without freeing them. After a few tests, I got to the conclusion that the Close() method of ManualResetEvent class doesn't always release the Win32 event handle immediately, and waits for the garbage collector to do that. Hence, running the GC explicitly releases the handles.

    -

    To make this problem less acute, I used a new approach. First, I wanted to create less number of handles, second, I wanted to reuse the handles I had already created. Therefore, I need not expose any WaitHandle but use them internally and then close them.

    -

    In order to create fewer handles, I created the ManualResetEvent objects only when the user asks for them (lazy creation). For example, if you don't use the GetResult() of the IWorkItemResult interface then a handle is not created. Using SmartThreadPool.WaitAll() and SmartThreadPool.WaitAny() creates a handle.

    -

    The work item queue created a lot of handles since each new wait for a work item created a new ManualResetEvent. Hence, a handle for each work item. The waiters of the queue are always the same threads and a thread cannot wait more than once. So now, every thread in the thread pool has its own ManualResetEvent and reuses it. To avoid coupling of the work items queue and the thread pool implementation, the work items queue stores a context inside the TLS (Thread Local Storage) of the thread.

    -
  • Work item can have a PostExecute callback. This is a method that will be called right after the work item execution has been completed. -

    A PostExecute is a callback method that is called right after the work item execution has been completed. It runs in the same context of the thread that executed the work item. The user can choose the cases in which the PostExecute is called. The options are represented in the CallToPostExecute flagged enumerator:

    [Flags]
    +
  • Usage of minimum number of Win32 event handles, so the handle count of the application won't explode. +

    The seventh feature is a result of Kevin's comment on the earlier version of Smart Thread Pool. It seemed that the test application consumed a lot of handles (Handle Count in the Task Manager) without freeing them. After a few tests, I got to the conclusion that the Close() method of ManualResetEvent class doesn't always release the Win32 event handle immediately, and waits for the garbage collector to do that. Hence, running the GC explicitly releases the handles.

    +

    To make this problem less acute, I used a new approach. First, I wanted to create less number of handles, second, I wanted to reuse the handles I had already created. Therefore, I need not expose any WaitHandle but use them internally and then close them.

    +

    In order to create fewer handles, I created the ManualResetEvent objects only when the user asks for them (lazy creation). For example, if you don't use the GetResult() of the IWorkItemResult interface then a handle is not created. Using SmartThreadPool.WaitAll() and SmartThreadPool.WaitAny() creates a handle.

    +

    The work item queue created a lot of handles since each new wait for a work item created a new ManualResetEvent. Hence, a handle for each work item. The waiters of the queue are always the same threads and a thread cannot wait more than once. So now, every thread in the thread pool has its own ManualResetEvent and reuses it. To avoid coupling of the work items queue and the thread pool implementation, the work items queue stores a context inside the TLS (Thread Local Storage) of the thread.

    +
  • Work item can have a PostExecute callback. This is a method that will be called right after the work item execution has been completed. +

    A PostExecute is a callback method that is called right after the work item execution has been completed. It runs in the same context of the thread that executed the work item. The user can choose the cases in which the PostExecute is called. The options are represented in the CallToPostExecute flagged enumerator:

    [Flags]
     public enum CallToPostExecute
     {
         Never                    = 0x00,
    @@ -507,45 +523,45 @@ public enum CallToPostExecute
     }

    Explanation:

      -
    • Never – Don't run the PostExecute. -
    • WhenWorkItemCanceled - Run the PostExecute only when the work item has been canceled. -
    • WhenWorkItemNotCanceled - Run the PostExecute only when the work item has not been canceled. -
    • Always – Always run the PostExecute.
    -

    The SmartThreadPool has a default CallToPostExecute value of CallToPostExecute.Always. This can be changed during the construction of the SmartThreadPool in the STPStartInfo class argument. Another way to give the CallToPostExecute value is in one of the SmartThreadPool.QueueWorkItem overloads. Note that as opposed to the WorkItem execution, if an exception has been thrown during the PostExecute, then it is ignored. The PostExecute is a delegate with the following signature:

    public delegate void PostExecuteWorkItemCallback(IWorkItemResult wir);
    -

    As you can see, the PostExecute receives as an argument of type IWorkItemResult. It can be used to get the result of the work item, or any other information made available by the IWorkItemResult interface.

    -
  • The user can choose to automatically dispose off the state object that accompanies the work item. -

    When the user calls the QueueWorkItem, he/she can provide a state object. The state object usually stores specific information, such as arguments, that should be used within the WorkItemCallback delegate.

    +
  • Never – Don't run the PostExecute. +
  • WhenWorkItemCanceled - Run the PostExecute only when the work item has been canceled. +
  • WhenWorkItemNotCanceled - Run the PostExecute only when the work item has not been canceled. +
  • Always – Always run the PostExecute.
  • +

    The SmartThreadPool has a default CallToPostExecute value of CallToPostExecute.Always. This can be changed during the construction of the SmartThreadPool in the STPStartInfo class argument. Another way to give the CallToPostExecute value is in one of the SmartThreadPool.QueueWorkItem overloads. Note that as opposed to the WorkItem execution, if an exception has been thrown during the PostExecute, then it is ignored. The PostExecute is a delegate with the following signature:

    public delegate void PostExecuteWorkItemCallback(IWorkItemResult wir);
    +

    As you can see, the PostExecute receives as an argument of type IWorkItemResult. It can be used to get the result of the work item, or any other information made available by the IWorkItemResult interface.

    +
  • The user can choose to automatically dispose off the state object that accompanies the work item. +

    When the user calls the QueueWorkItem, he/she can provide a state object. The state object usually stores specific information, such as arguments, that should be used within the WorkItemCallback delegate.

    The state object life time depends on its contents and the user's application. Sometimes, it is useful to dispose off the state object just after the work item has been completed. Especially if it contains unmanaged resources.

    -

    For this reason, I added a boolean to the SmartThreadPool that indicates to call Dispose on the state object when the work item has been completed. The boolean is initialized when the thread pool is constructed with the STPStartInfo. The Dispose is called only if the state object implements the IDisposable interface. The Dispose is called after the WorkItem has been completed and its PostExecute has run (if a PostExecute exists). The state object is disposed even if the work item has been canceled or the thread pool has been shutdown.

    +

    For this reason, I added a boolean to the SmartThreadPool that indicates to call Dispose on the state object when the work item has been completed. The boolean is initialized when the thread pool is constructed with the STPStartInfo. The Dispose is called only if the state object implements the IDisposable interface. The Dispose is called after the WorkItem has been completed and its PostExecute has run (if a PostExecute exists). The state object is disposed even if the work item has been canceled or the thread pool has been shutdown.

    - Note that this feature only applies to the state argument that + Note that this feature only applies to the state argument that comes with WorkItemCallback, it doesn't apply to the - arguments supplied in Action<...> and Func<...> arguments!!!

    -
  • The user can wait for the Smart Thread Pool / Work Items Group + arguments supplied in Action<...> and Func<...> arguments!!!

    +
  • The user can wait for the Smart Thread Pool / Work Items Group to become idle.

    This feature enables the user to wait for a Smart Thread Pool or a Work Items Group to become idle. They become idle when the work items queue is empty and all the threads have completed executing all their work items.

    -

    This is useful in case you want to run a batch of work items and then wait for all of them to complete. It saves you from handling the IWorkItemResult objects in case you just want to wait for all of the work items to complete.

    +

    This is useful in case you want to run a batch of work items and then wait for all of them to complete. It saves you from handling the IWorkItemResult objects in case you just want to wait for all of the work items to complete.

    The SmartThreadPool and WorkItemsGroup classes both implement the IWorkItemsGroup interface which define the WaitForIdle methods.

    - To take advantage of this feature, use the IWorkItemsGroup.WaitForIdle() method (Both SmartThreadPool and WorkItemsGroup implement the IWorkItemsGroup interface - which define the WaitForIdle methods). It has several overloads which provide a timeout argument. The WaitForIdle() method is not static and should be used on a SmartThreadPool instance.

    -

    The SmartThreadPool always keeps track of how many work items it has. When a new work item is queued, the number is incremented. When a thread completes a work item, the number is decremented. The total number of work items includes the work items in the queue and the work items that the threads are currently working on.

    -

    The WaitForIdle() mechanism works with a private ManualResetEvent. When a work item is queued, the ManualResetEvent is reset (changed to non signaled state). When the work items count becomes zero (initial state of the Smart Thread Pool), the ManualResetEvent is set (changed to signaled state). The WaitForIdle() method just waits for the ManualResetEvent to implement its functionality.

    + To take advantage of this feature, use the IWorkItemsGroup.WaitForIdle() method (Both SmartThreadPool and WorkItemsGroup implement the IWorkItemsGroup interface + which define the WaitForIdle methods). It has several overloads which provide a timeout argument. The WaitForIdle() method is not static and should be used on a SmartThreadPool instance.

    +

    The SmartThreadPool always keeps track of how many work items it has. When a new work item is queued, the number is incremented. When a thread completes a work item, the number is decremented. The total number of work items includes the work items in the queue and the work items that the threads are currently working on.

    +

    The WaitForIdle() mechanism works with a private ManualResetEvent. When a work item is queued, the ManualResetEvent is reset (changed to non signaled state). When the work items count becomes zero (initial state of the Smart Thread Pool), the ManualResetEvent is set (changed to signaled state). The WaitForIdle() method just waits for the ManualResetEvent to implement its functionality.

    See the example below.

    -
  • The exception handling is changed, so if a work item throws an exception, it is rethrown at GetResult(), rather than firing an UnhandledException event. Note that PostExecute exceptions are always ignored. -

    After I did some reading about delegates and their implementation, I decided to change the way the SmartThreadPool treats exceptions. In the previous versions, I used an event driven mechanism. Entities were registered to the SmartThreadPool.UnhandledException event, and when a work item threw an exception, this event was fired. This is the behavior of Toub’s thread pool.

    -

    .NET delegates behave differently. Instead of using an event driven mechanism, it re-throws the exception of the delegated method at the EndInvoke(). Similarly, the SmartThreadPool exception mechanism is changed so that exceptions are no longer fired by the UnhandledException event, but rather re-thrown again when IWorkItemResult.GetResult() is called.

    -

    Note that exceptions slow down .NET and degrade the performance. .NET works faster when no exceptions are thrown at all. For this reason, I added an output parameter to some of the GetResult() overloads, so the exception can be retrieved rather than re-thrown. The work item throws the exception anyway, so re-throwing it will be a waste of time. As a rule of thumb, it is better to use the output parameter than catch the re-thrown exception.

    -

    The GetResult() can be called unlimited number of times and it re-throws the same exception each time.

    -

    Note that PostExecute is called, as and when needed, even if the work item has thrown an exception. Of course, PostExecute implementation should handle exceptions if it calls GetResult().

    -

    Also note that if the PostExecute throws an exception then its exception is ignored.

    +
  • The exception handling is changed, so if a work item throws an exception, it is rethrown at GetResult(), rather than firing an UnhandledException event. Note that PostExecute exceptions are always ignored. +

    After I did some reading about delegates and their implementation, I decided to change the way the SmartThreadPool treats exceptions. In the previous versions, I used an event driven mechanism. Entities were registered to the SmartThreadPool.UnhandledException event, and when a work item threw an exception, this event was fired. This is the behavior of Toub’s thread pool.

    +

    .NET delegates behave differently. Instead of using an event driven mechanism, it re-throws the exception of the delegated method at the EndInvoke(). Similarly, the SmartThreadPool exception mechanism is changed so that exceptions are no longer fired by the UnhandledException event, but rather re-thrown again when IWorkItemResult.GetResult() is called.

    +

    Note that exceptions slow down .NET and degrade the performance. .NET works faster when no exceptions are thrown at all. For this reason, I added an output parameter to some of the GetResult() overloads, so the exception can be retrieved rather than re-thrown. The work item throws the exception anyway, so re-throwing it will be a waste of time. As a rule of thumb, it is better to use the output parameter than catch the re-thrown exception.

    +

    The GetResult() can be called unlimited number of times and it re-throws the same exception each time.

    +

    Note that PostExecute is called, as and when needed, even if the work item has thrown an exception. Of course, PostExecute implementation should handle exceptions if it calls GetResult().

    +

    Also note that if the PostExecute throws an exception then its exception is ignored.

    See the example below.

    -
  • Work items have priority. -

    Work items priority enables the user to order work items at run time. Work items are ordered by their priority. High priority is treated first. There are five priorities:

    public enum WorkItemPriority 
    +
  • Work items have priority. +

    Work items priority enables the user to order work items at run time. Work items are ordered by their priority. High priority is treated first. There are five priorities:

    public enum WorkItemPriority 
     { 
         Lowest, 
         BelowNormal, 
    @@ -553,13 +569,13 @@ public enum CallToPostExecute
         AboveNormal, 
         Highest,
     }
    -

    The default priority is Normal.

    +

    The default priority is Normal.

    The implementation of priorities is quite simple. Instead of using one queue that keeps the work items sorted inside, I used one queue for each priority. Each queue is a FIFO. When the user enqueues a work item, the work item is added to the queue with a matching priority. When a thread dequeues a work item, it looks for the highest priority queue that is not empty.

    This is the easiest solution to sort the work items.

    -
  • The caller thread's HTTP context can be used when the work item is executed. +
  • The caller thread's HTTP context can be used when the work item is executed.

    This feature improves 6, and was implemented by Steven T. I just replaced my code with that implementation.

    With this feature the Smart Thread Pool can be used with ASP.NET to pass the context of HTTP between the caller thread and the thread in the pool that will execute the work item.

    -
  • Work items group. +
  • Work items group.

    This feature enables the user to execute a group of work items specifying the maximum level of concurrency.

    For example, assume that your application uses several resources, the resources are not thread safe so only one thread can use a resource at a time. There are a @@ -575,7 +591,7 @@ public enum CallToPostExecute according to the load of work items.

    Here is a code snippet to show how it works:

    -
    ...
    +
    ...
     
     // Create a SmartThreadPool
     SmartThreadPool smartThreadPool = new SmartThreadPool();
    @@ -600,12 +616,12 @@ void Print(Printer printer, Document document) {...}
     
     ...

    As you can see from the snippet a Work Items Group is attached to an instance of a Smart Thread Pool. The Work Items Group doesn't have threads of its own, but rather uses the threads of the Smart Thread Pool. It also has an interface similar to the Smart Thread Pool, so it can be used in the same way and replaced when needed.

    -

    The WorkItemsGroup has a priority queue (the same as the SmartThreadPool). The queue stores the work items of the WorkItemsGroup. The WorkItemsGroup dequeues the work item with the highest priority at the head of the queue and queues it into the SmartThreadPool with the same priority.

    -

    The WorkItemsGroup is responsible for managing the maximum level of concurrency of its work items. Once a work item is queued into the WorkItemsGroup, it checks how many work items it has in the SmartThreadPool. If this number is less than the maximum level of concurrency, it queues the work item into the SmartThreadPool. If this number is equal (it cannot be greater) then the WorkItemsGroup stores the work item in its own priority queue.

    -

    In case the WorkItemsGroup is created in suspend mode, it will store the work items in its queue until it is started. When it is started it will queue the work items into the SmartThreadPool up to the maximum level of concurrency.

    -

    Note that the WorkItemsGroup only has a maximum level of concurrency and not a minimum or exact value. It is possible to have a concurrency level of 3, and have non work items executing, since they are waiting in the SmartThreadPool queue.

    -

    To accomplish the concurrency level, the WorkItemsGroup registers to the completion event of its work items. The event is used internally and is not exposed to the user. Once registered, the WorkItemsGroup will get an event when its work item is completed. The event will trigger the WorkItemsGroup to queue more work items into the SmartThreadPool. The event is the only way to accomplish the concurrency level. When I tried to do it with PostExecute I got fluctuating WaitForIdle.

    -

    Another advantage of the WorkItemsGroup is that it can cancel all its work items that haven't been executed yet in one method with a complexity of O(1). The WorkItemsGroup does so by attaching an object to each one of its work items that indicates if the WorkItemsGroup has been cancelled. When a work item is about to be executed, it is asked for its current state (InQueue, InProgress, Completed, or Canceled). The final state considers this object's value to know if the work item was cancelled.

    +

    The WorkItemsGroup has a priority queue (the same as the SmartThreadPool). The queue stores the work items of the WorkItemsGroup. The WorkItemsGroup dequeues the work item with the highest priority at the head of the queue and queues it into the SmartThreadPool with the same priority.

    +

    The WorkItemsGroup is responsible for managing the maximum level of concurrency of its work items. Once a work item is queued into the WorkItemsGroup, it checks how many work items it has in the SmartThreadPool. If this number is less than the maximum level of concurrency, it queues the work item into the SmartThreadPool. If this number is equal (it cannot be greater) then the WorkItemsGroup stores the work item in its own priority queue.

    +

    In case the WorkItemsGroup is created in suspend mode, it will store the work items in its queue until it is started. When it is started it will queue the work items into the SmartThreadPool up to the maximum level of concurrency.

    +

    Note that the WorkItemsGroup only has a maximum level of concurrency and not a minimum or exact value. It is possible to have a concurrency level of 3, and have non work items executing, since they are waiting in the SmartThreadPool queue.

    +

    To accomplish the concurrency level, the WorkItemsGroup registers to the completion event of its work items. The event is used internally and is not exposed to the user. Once registered, the WorkItemsGroup will get an event when its work item is completed. The event will trigger the WorkItemsGroup to queue more work items into the SmartThreadPool. The event is the only way to accomplish the concurrency level. When I tried to do it with PostExecute I got fluctuating WaitForIdle.

    +

    Another advantage of the WorkItemsGroup is that it can cancel all its work items that haven't been executed yet in one method with a complexity of O(1). The WorkItemsGroup does so by attaching an object to each one of its work items that indicates if the WorkItemsGroup has been cancelled. When a work item is about to be executed, it is asked for its current state (InQueue, InProgress, Completed, or Canceled). The final state considers this object's value to know if the work item was cancelled.

    The Work Items Group can also be use as a conjuction point. Say you want to accoplish a task by splitting to a subtasks. Once the subtasks are completed a new task is @@ -615,15 +631,15 @@ void Print(Printer printer, Document document) {...} See the examples below.

    See WorkItemsGroupDemo demo in the source code solution.

    -

    -
  • The caller can create thread pools and work items groups in suspended state. +

    +
  • The caller can create thread pools and work items groups in suspended state.

    When a Smart Thread Pool is created, by default, it starts its threads immediately. However, sometimes you need to queue a few work items and only then start executing them.

    -

    In these cases, you can create the Smart Thread Pool and the Work Items Group in a suspended state. When you need to execute the work items, just call the Start() method. The same method exists in the Work Items Group for the same purpose.

    +

    In these cases, you can create the Smart Thread Pool and the Work Items Group in a suspended state. When you need to execute the work items, just call the Start() method. The same method exists in the Work Items Group for the same purpose.

    Note that if you create a suspended Work Items Group in a suspended Smart Thread Pool, starting the Work Items Group won't execute the work items until the Smart Thread Pool is started.

    -
  • Threads have priority. -

    The STPStartInfo contains a property that defines the priority in which the threads are started in the SmartThreadPool. Use it if you know what you are doing. Playing with threads priority may end up with dead locks, live lock, and days locked :-(.

    +
  • Threads have priority. +

    The STPStartInfo contains a property that defines the priority in which the threads are started in the SmartThreadPool. Use it if you know what you are doing. Playing with threads priority may end up with dead locks, live lock, and days locked :-(.

    -
  • The MaxThreads/MinThreads/Concurrency can +
  • The MaxThreads/MinThreads/Concurrency can be changed at run time.

    This addition allows the user to control the concurrency of work items execution. @@ -634,39 +650,39 @@ void Print(Printer printer, Document document) {...} decrement the concurrency.

    - This option is available in the SmartThreadPool and in the WorkItemsGroup with the IWokItemsGroup interface: + This option is available in the SmartThreadPool and in the WorkItemsGroup with the IWokItemsGroup interface:

    -
    public interface IWorkItemsGroup
    +
    public interface IWorkItemsGroup
     {
         ...
         int Concurrency { get; set; }
         ...
     }
    -

    The value of Concurrency must be positive.

    +

    The value of Concurrency must be positive.

    -

    Although the Concurrency has the same meaning and the same behavior in the SmartThreadPool and in the WorkItemsGroup it’s implemented differently.

    +

    Although the Concurrency has the same meaning and the same behavior in the SmartThreadPool and in the WorkItemsGroup it’s implemented differently.

    -

    The SmartThreadPool’s Concurrency is equivalent to the MaxThreads property. When the Concurrency is incremented, the SmartThreadPool can create more threads to handle its work items up to the Concurrency limit. The creation of thread, in this case, is immediate. The threads are still created as explained in section 2.

    +

    The SmartThreadPool’s Concurrency is equivalent to the MaxThreads property. When the Concurrency is incremented, the SmartThreadPool can create more threads to handle its work items up to the Concurrency limit. The creation of thread, in this case, is immediate. The threads are still created as explained in section 2.

    -

    When the Concurrency is decrement, the SmartThreadPool doesn’t create new threads and let existing threads to be terminated in order decrement the number of threads in the thread pool. Note that the lowering the Concurrency may take a while effect, since we need to wait for work items to complete. The SmartThreadPool doesn’t abort a thread actively, but wait passively until it quits.

    +

    When the Concurrency is decrement, the SmartThreadPool doesn’t create new threads and let existing threads to be terminated in order decrement the number of threads in the thread pool. Note that the lowering the Concurrency may take a while effect, since we need to wait for work items to complete. The SmartThreadPool doesn’t abort a thread actively, but wait passively until it quits.

    -

    The WorkItemsGroup’s Concurrency is responsible to how many work items may be handled in parallel in the SmartThreadPool as explained in section 14. When the Concurrency is incremented more work items are queued to the SmartThreadPool. When the Concurrency is decremented, the WorkItemsGroup stops to queue work items until the number of work items in the SmartThreadPool of this WorkItemsGroup is lower than the WorkItemsGroup’s Concurrency.

    +

    The WorkItemsGroup’s Concurrency is responsible to how many work items may be handled in parallel in the SmartThreadPool as explained in section 14. When the Concurrency is incremented more work items are queued to the SmartThreadPool. When the Concurrency is decremented, the WorkItemsGroup stops to queue work items until the number of work items in the SmartThreadPool of this WorkItemsGroup is lower than the WorkItemsGroup’s Concurrency.

    -

    In addition the SmartThreadPool also let the MinThreads property to be changed after its creation. When the MinThreads is created the number of threads in the pool is raised so it will be at least MinThreads.

    +

    In addition the SmartThreadPool also let the MinThreads property to be changed after its creation. When the MinThreads is created the number of threads in the pool is raised so it will be at least MinThreads.

    -

    The number of MaxThreads must be greater or equal to MinThreads. If MaxThreads is set to a number lower than MinThreads than MinThreads is also set to the new value of MaxThreads. And vice versa for MinThreads.

    +

    The number of MaxThreads must be greater or equal to MinThreads. If MaxThreads is set to a number lower than MinThreads than MinThreads is also set to the new value of MaxThreads. And vice versa for MinThreads.

    -
  • Improved the Cancel behavior. +
  • Improved Cancel behavior.

    (See section 5)

    -
  • Added events for initialization and termination of threads.

    +

  • Threads initialization and termination generate events.

    This functionality enables the user to execute code when a thread is created or terminated in the thread pool. The code is executed within the thread’s context. This feature is exposed as new events in the SmartThreadPool class:

    -
    // A delegate to call after a thread is created, but before it's first use.
    +
    // A delegate to call after a thread is created, but before it's first use.
     public delegate void ThreadInitializationHandler();
     
     // A delegate to call when a thread is about to exit, after it is no longer 
    @@ -678,7 +694,7 @@ public event ThreadInitializationHandler OnThreadInitialization
     
     public event ThreadTerminationHandler OnThreadTermination;
     {...}
    -
    +

    The OnThreadInitialization event is fired when a thread is created and added to the threads pool. The event is called from the created thread. @@ -692,118 +708,176 @@ The OnThreadTermination event is fired when a thread leaves the threads pool. The event is called from the terminated thread. In this event the user has the opportunity to clean up the resources that were initialized earlier in the OnThreadInitialization event. -

  • -
  • Added support for Windows CE (limited)
  • +

  • +
  • Supports Windows CE (limited)
  • The SmartThreadPool project has a similar project named SmartThreadPoolCE. This version of the SmartThreadPool can be run on Windows CE.

    It has the same features as the PC version, but it doesn't fully work yet. I still have an issue with the threads scheduling, since the thread idle stuff explained in section 2 doesn't work on Windows CE.

    -
  • Added IsIdle flag to the SmartThreadPool and to the IWorkItemsGroup
  • -

    This flag enables the user to poll the Smart Thread Pool / Work Items Group for - idle.

    -
  • Added support for Action<T> - and Func<T> (strongly typed work items)
  • + +

    + +
  • SmartThreadPool and IWorkItemsGroup has IsIdle flag
  • +

    This flag enables the user to poll the Smart Thread Pool / Work Items Group if they are idle.

    +
  • Supports Action<T> and Func<T> (strongly typed work items)
  • (See section 3)

    -

    +
  • Supports Silverlight
  • +

    +

    Add reference to SmartThreadPoolSL.dll in your code and use it.

    +

    +
  • Supports Mono
  • +

    Add reference to SmartThreadPoolMono.dll in your code and use it.

    +

    Note that the binaries of Mono were compiled on Windows with Visual Studio 2008

    +

    + +
  • Internal performance counters
  • +

    The internal performance counter should be used on platforms that don't support Performance Counters, +such as WindowsCE, Silverlight, and Mono.

    +

    The internal performance counters are variables inside STP that collects the data. To enable them set +the STPStartInfo.EnableLocalPerformanceCounters to true. I use this feature in the new demos. (WindowsCE, Silverlight, and Momo).

    +
  • Join, Choice, and Pipe
  • +

    The new methods are added to the SmartThreadPool class and implemented using WorkItemsGroup. Their purpose is +to simplfy the initiation of a parallel task.

    +
      +
    • Join - Executes several work items and waits for all of them to complete. (Join example)
    • +
    • Choice - Executes several work items and returns when the first one completes. (Choice example)
    • +
    • Pipe - Executes several work items sequently and wait until the last work item completes. (Pipe example)
    • +

    When to use?

    The Smart Thread Pool is good when your work items don't do too much, but wait for events, IOs, sockets, etc. This means that the work items don't use CPU, but run for a long time. It is also good when you don't need to keep alive too many threads in the air all the time. If your work items do a short time work, then use the .NET ThreadPool. If you have a constant heavy load of work, then use Toub's thread pool and define the maximum number of threads accordingly.

    - +

    How to use?

    +

    When the Smart Thread Pool or Work Items Group is created, it requires a few parameters; when a value is not provided, a default value is used.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - -
    DescriptionValue nameDefault valueSmart Thread PoolWork Items Group
    Idle timeoutIdleTimeout60 secondsUsedNot used
    Maximum number of threadsMaxWorkerThreads25UsedNot used
    Minimum number of threadsMinWorkerThreads0UsedNot used
    Use caller thread call contextUseCallerCallContextfalseUsedUsed
    Use caller thread HTTP contextUseCallerHttpContextfalseUsedUsed
    Dispose of the state objectsDisposeOfStateObjectsfalseUsedUsed
    Call to PostExecuteCallToPostExecuteCallToPostExecute.AlwaysUsedUsed
    PostExecute methodPostExecuteWorkItemCallbacknull (Do nothing)UsedUsed
    Start suspendedStartSuspendedfalseUsedUsed
    Fill state with args +
    Value nameDefault valueSmart Thread PoolWork Items GroupDescription
    IdleTimeout60 secondsUsedNot usedIdle timeout
    MaxWorkerThreads25UsedNot usedMaximum number of threads
    MinWorkerThreads0UsedNot usedMinimum number of threads
    UseCallerCallContextfalseUsedUsedUse caller thread call context
    UseCallerHttpContextfalseUsedUsedUse caller thread HTTP context
    DisposeOfStateObjectsfalseUsedUsedDispose of the state objects (If the state implements IDisposable)
    CallToPostExecuteCallToPostExecute.AlwaysUsedUsedCall to PostExecute
    PostExecuteWorkItemCallbacknull (Do nothing)UsedUsedPostExecute method
    StartSuspendedfalseUsedUsedStart suspended
    FillStateWithArgsfalseUsedUsedFill state with args
    - (Action<T> & Func<T>)
    FillStateWithArgsfalseUsedUsed
    Thread priority in thread poolThreadPriorityThreadPriority.NormalUsedNot used
    Work item default priorityWorkItemPriority.NormalUsedUsed
    + (Action<T> & Func<T>) + + +ThreadPriority +ThreadPriority.Normal +Used +Not used +Thread priority in thread pool
    (Not supported in Mono) + + +WorkItemPriority +WorkItemPriority.Normal +Used +Used +Work item default priority + + +PerformanceCounterInstanceName +null +Used +Not used +Performance counter instance name + + +EnableLocalPerformanceCounters +false +Used +Not used +Enable local performance counters
    (For platforms which don't support performance + counters) + + +  +  +  +  +  +

    Once defined in the construction, they cannot be changed. So, choose their values according to your needs. The minimum number of threads should be proportional to the number of work items that you want to handle at normal times. The maximum number of threads should be proportional to the number of work items that you want to handle at peak times. The idle timeout should be proportional to the peak length time.

    Code examples

    -

    Creating a Smart Thread Pool instance:

    SmartThreadPool smartThreadPool = 
    +

    Creating a Smart Thread Pool instance:

    SmartThreadPool smartThreadPool = 
      new SmartThreadPool(
         10*1000,    // Idle timeout in milliseconds
         25,         // Threads upper limit
         5,          // Threads lower limit
         true);      // Use caller thread context
    -

    Another way to create an instance:

    // Create a STPStartInfo object
    +

    Another way to create an instance:

    // Create a STPStartInfo object
     STPStartInfo stpStartInfo = new STPStartInfo();
     
     // Change the defaults of the STPStartInfo object
    @@ -813,7 +887,7 @@ stpStartInfo.DisposeOfStateObjects = true;
     SmartThreadPool smartThreadPool = 
             new SmartThreadPool(stpStartInfo);

    Using the Smart Thread Pool:

    -

    The following snippet is a simple example. The user queues a work item and then gets the result. Note that the Result property blocks until a result is available or the work item is cancelled:

    public class SimpleExample
    +

    The following snippet is a simple example. The user queues a work item and then gets the result. Note that the Result property blocks until a result is available or the work item is cancelled:

    public class SimpleExample
     {
         public void DoWork(int [] numbers) 
         { 
    @@ -841,7 +915,7 @@ SmartThreadPool smartThreadPool =
             return average;
         }
     }
    -

    This example shows how you can wait for specific work items to complete. The user queues two work items, waits for both of them to complete, and then gets the results:

    public class WaitForAllExample
    +

    This example shows how you can wait for specific work items to complete. The user queues two work items, waits for both of them to complete, and then gets the results:

    public class WaitForAllExample
     {
         public void DoWork() 
         { 
    @@ -877,7 +951,7 @@ SmartThreadPool smartThreadPool =
             return 2;
         }
     }
    -

    This example shows how you can wait for one of the specific work items to complete. The user queues two work items, waits for one of them to complete, and then gets its result:

    public class WaitForAnyExample
    +

    This example shows how you can wait for one of the specific work items to complete. The user queues two work items, waits for one of them to complete, and then gets its result:

    public class WaitForAnyExample
     {
         public void DoWork() 
         { 
    @@ -914,7 +988,7 @@ SmartThreadPool smartThreadPool =
             return 1;
         }
     }
    -

    The following example shows the use of WaitForIdle(). We just queue all the work items and then wait for all of them to complete. Note that we ignore the results of the work items:

    public class WaitForIdleExample
    +

    The following example shows the use of WaitForIdle(). We just queue all the work items and then wait for all of them to complete. Note that we ignore the results of the work items:

    public class WaitForIdleExample
     {
         public void DoWork(object [] states) 
         { 
    @@ -938,7 +1012,7 @@ SmartThreadPool smartThreadPool =
             return null;
         }
     }
    -

    The following example shows how to handle exceptions. Pay attention to the Result property that throws WorkItemResultException and not the real exception:

    public class CatchExceptionExample
    +

    The following example shows how to handle exceptions. Pay attention to the Result property that throws WorkItemResultException and not the real exception:

    public class CatchExceptionExample
     {
         public void DoWork() 
         { 
    @@ -965,7 +1039,7 @@ SmartThreadPool smartThreadPool =
             return x / y;
         }
     }
    -

    This is another example that shows how to handle exceptions. It is better than the previous one because it is faster. .NET works fast when everything is OK. When .NET needs to deal with exceptions, it becomes slower:

    public class GetExceptionExample
    +

    This is another example that shows how to handle exceptions. It is better than the previous one because it is faster. .NET works fast when everything is OK. When .NET needs to deal with exceptions, it becomes slower:

    public class GetExceptionExample
     {
         public void DoWork() 
         { 
    @@ -989,7 +1063,7 @@ SmartThreadPool smartThreadPool =
             return x / y;
         }
     }
    -

    The next example shows how to create a Work Items Group and use it:

    public class WorkItemsGroupExample
    +

    The next example shows how to create a Work Items Group and use it:

    public class WorkItemsGroupExample
     {
         public void DoWork(object [] states)
         { 
    @@ -1020,7 +1094,7 @@ SmartThreadPool smartThreadPool =
             return null;
         }
     }
    -

    The next example shows how to create a suspended Smart Thread Pool:

    public class SuspendedSTPStartExample
    +

    The next example shows how to create a suspended Smart Thread Pool:

    public class SuspendedSTPStartExample
     {
         public void DoWork(object [] states) 
         { 
    @@ -1051,7 +1125,7 @@ SmartThreadPool smartThreadPool =
             return null;
         }
     }
    -

    The next example shows how to create a suspended Work Items Group:

    public class SuspendedWIGStartExample
    +

    The next example shows how to create a suspended Work Items Group:

    public class SuspendedWIGStartExample
     {
         public void DoWork(object [] states) 
         { 
    @@ -1086,7 +1160,7 @@ SmartThreadPool smartThreadPool =
         }
     }

    - This example shows how to get the Work Items Group's OnIdle event:

    +    This example shows how to get the Work Items Group's OnIdle event:

     public class OnWIGIdleEventExample
     {
         public void DoWork(object [] states) 
    @@ -1119,77 +1193,169 @@ public class OnWIGIdleEventExample
             Debug.WriteLine("WIG is idle");
         }
     }
    +

    This example shows how to use Join

    +public class JoinExample
    +{
    +    public void DoWork() 
    +    { 
    +        SmartThreadPool stp = new SmartThreadPool();
    +
    +        stp.Join(DoSomeWork1, DoSomeWork2);
    +
    +        smartThreadPool.Shutdown();
    +    } 
    +
    +    private void DoSomeWork1()
    +    { 
    +        // ...
    +    }
    +
    +    private void DoSomeWork2()
    +    { 
    +        // ...
    +    }
    +   
    +}
    + +

    This example shows how to use Choice

    +public class ChoiceExample
    +{
    +    public void DoWork() 
    +    { 
    +        SmartThreadPool stp = new SmartThreadPool();
    +
    +        int index = stp.Choice(GetDataFromA, GetDataFromB);
    +
    +        if (index == 0)
    +        {
    +            // Got data from A
    +        }
    +        else if (index == 1)
    +        {
    +            // Got data from B
    +        }
    +
    +        smartThreadPool.Shutdown();
    +    } 
    +
    +    private void GetDataFromA()
    +    { 
    +        // ...
    +    }
    +
    +    private void GetDataFromB()
    +    { 
    +        // ...
    +    }
    +   
    +}
    + +

    This example shows how to use Pipe

    +public class PipeExample
    +{
    +    public void DoWork() 
    +    { 
    +        SmartThreadPool stp = new SmartThreadPool();
    +        
    +        int [] data = new int[2];
    +
    +        stp.Pipe(data, DoStep1, DoStep2);
    +
    +        smartThreadPool.Shutdown();
    +    } 
    +
    +    private void DoStep1(int [] data)
    +    { 
    +        data[0] = ...
    +    }
    +
    +    private void DoStep2(int [] data)
    +    { 
    +        data[1] = ...
    +    }
    +   
    +}
    +

    Disclaimer

    THIS CODE AND INFORMATION IS PROVIDED 'AS IS' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.

    History

      -
    • 7th Aug, 2004: Initial version. -
    • 14th Sep, 2004: Bug fixes: +
    • 7th Aug, 2004: Initial version. +
    • 14th Sep, 2004: Bug fixes:
        -
      1. Changed the start thread formula to 'if ((InUseThreads + WaitingCallbacks) > _workerThreads.Count)'. -
      2. Fixed handle leaks.
      -
    • 16th Oct, 2004: Added a few features: +
    • Changed the start thread formula to 'if ((InUseThreads + WaitingCallbacks) > _workerThreads.Count)'. +
    • Fixed handle leaks.
    • +
    • 16th Oct, 2004: Added a few features:
        -
      • Work items return result. -
      • Supports waiting synchronization for multiple work items. -
      • Work items can be cancelled. -
      • Passage of the caller thread's context to the thread in the pool. -
      • Minimal usage of Win32 handles. -
      • Minor bug fixes.
      -
    • 26th Dec, 2004: Changes: +
    • Work items return result. +
    • Supports waiting synchronization for multiple work items. +
    • Work items can be cancelled. +
    • Passage of the caller thread's context to the thread in the pool. +
    • Minimal usage of Win32 handles. +
    • Minor bug fixes.
    +
  • 26th Dec, 2004: Changes:
      -
    • Added PostExecute with options on which cases to call it. -
    • Added a WaitForIdle() method that waits until the work items queue is empty. -
    • Added option to dispose off the state objects. -
    • Updated the FireUnhandledException so it will be more robust. -
    • Removed static constructors. -
    • Added finalizers. -
    • Changed exceptions so that they are serializable. -
    • Fixed the bug in one of the SmartThreadPool constructors. -
    • Changed SmartThreadPool.WaitAll() so that it will support any number of waiters. The SmartThreadPool.WaitAny() is still limited by the .NET Framework. -
    • Changed exception handling so if a work item throws an exception, it is re-thrown at GetResult(), rather than firing an UnhandledException event. Note that PostExecute exceptions are always ignored.
    -
  • 25th Mar, 2005: Changes: +
  • Added PostExecute with options on which cases to call it. +
  • Added a WaitForIdle() method that waits until the work items queue is empty. +
  • Added option to dispose off the state objects. +
  • Updated the FireUnhandledException so it will be more robust. +
  • Removed static constructors. +
  • Added finalizers. +
  • Changed exceptions so that they are serializable. +
  • Fixed the bug in one of the SmartThreadPool constructors. +
  • Changed SmartThreadPool.WaitAll() so that it will support any number of waiters. The SmartThreadPool.WaitAny() is still limited by the .NET Framework. +
  • Changed exception handling so if a work item throws an exception, it is re-thrown at GetResult(), rather than firing an UnhandledException event. Note that PostExecute exceptions are always ignored.
  • +
  • 25th Mar, 2005: Changes:
      -
    • Fixed bug where the work items got lost. It happens especially when the idle timeout is small.
    -
  • 3rd Jul, 2005: Changes: +
  • Fixed bug where the work items got lost. It happens especially when the idle timeout is small.
  • +
  • 3rd Jul, 2005: Changes:
      -
    • Fixed bug where Enqueue() throws an exception when PopWaiter() returns null, hardly reconstructed.
    -
  • 16th Aug 2005: Changes: +
  • Fixed bug where Enqueue() throws an exception when PopWaiter() returns null, hardly reconstructed.
  • +
  • 16th Aug 2005: Changes:
      -
    • Fixed bug where the InUseThreads becomes negative while canceling work items.
    -
  • 31st Jan, 2006: Changes: +
  • Fixed bug where the InUseThreads becomes negative while canceling work items.
  • +
  • 31st Jan, 2006: Changes:
      -
    • Added work items priority. -
    • Removed support of chained delegates in callbacks and post executes (nobody really uses this). -
    • Added work items groups. -
    • Added work items group's idle event. -
    • Changed SmartThreadPool.WaitAll() behavior so that when it gets an empty array it returns true rather than throwing an exception. -
    • Added option to start the Smart Thread Pool and the Work Items Groups as suspended. -
    • Exception behavior changed (again). The real exception is returned by an inner exception. -
    • Added option to keep the HTTP context of the caller thread. (Thanks to Steven T.). -
    • Added performance counters. -
    • Added priority to the threads in the pool.
    -
  • 13th Feb, 2006: Changes: +
  • Added work items priority. +
  • Removed support of chained delegates in callbacks and post executes (nobody really uses this). +
  • Added work items groups. +
  • Added work items group's idle event. +
  • Changed SmartThreadPool.WaitAll() behavior so that when it gets an empty array it returns true rather than throwing an exception. +
  • Added option to start the Smart Thread Pool and the Work Items Groups as suspended. +
  • Exception behavior changed (again). The real exception is returned by an inner exception. +
  • Added option to keep the HTTP context of the caller thread. (Thanks to Steven T.). +
  • Added performance counters. +
  • Added priority to the threads in the pool.
  • +
  • 13th Feb, 2006: Changes:
      -
    • Fixed the demo, so that it won't crash with exception on start. -
    • Added a call to dispose off the performance counters so that there is no performance counter leak. -
    • Added exception catch in case the performance counters cannot be created.
    • +
    • Fixed the demo, so that it won't crash with exception on start. +
    • Added a call to dispose off the performance counters so that there is no performance counter leak. +
    • Added exception catch in case the performance counters cannot be created.
    -
  • -
  • 16th May 2008: Changes +
  • +
  • 16th May 2008: Changes
      -
    • Changed the dispose behavior and removed the Finalizers.
    • -
    • Enabled the change of the MaxThreads and MinThreads at run time.
    • -
    • Enabled the change of the Concurrency of a IWorkItemsGroup at run time If the IWorkItemsGroup is a SmartThreadPool then the Concurrency refers to the MaxThreads.
    • -
    • Improved the cancel behavior.
    • -
    • Added events for thread creation and termination.
    • -
    • Fixed the HttpContext context capture.
    • -
    • Changed internal collections so they use generic collections
    • -
    • Added IsIdle flag to the SmartThreadPool and IWorkItemsGroup
    • -
    • Added support for WinCE
    • -
    • Added support for Action<T> and Func<T>
    • +
    • Changed the dispose behavior and removed the Finalizers.
    • +
    • Enabled the change of the MaxThreads and MinThreads at run time.
    • +
    • Enabled the change of the Concurrency of a IWorkItemsGroup at run time If the IWorkItemsGroup is a SmartThreadPool then the Concurrency refers to the MaxThreads.
    • +
    • Improved the cancel behavior.
    • +
    • Added events for thread creation and termination.
    • +
    • Fixed the HttpContext context capture.
    • +
    • Changed internal collections so they use generic collections
    • +
    • Added IsIdle flag to the SmartThreadPool and IWorkItemsGroup
    • +
    • Added support for WinCE
    • +
    • Added support for Action<T> and Func<T>
    • +
    +
  • 7th April 2009: Changes + +
      +
    • Added support for Silverlight and Mono.
    • +
    • Added Join, Choice, and Pipe to SmartThreadPool.
    • +
    • Added local performance counters (for Mono, Silverlight, and WindowsCE)
    • +
    • Changed duration measures from DateTime.Now to Stopwatch.
    • +
    • Queues changed from System.Collections.Queue to System.Collections.Generic.LinkedList<T>.
  • diff --git a/Docs/WindowsCE.jpg b/Docs/WindowsCE.jpg new file mode 100644 index 0000000..1caf7df Binary files /dev/null and b/Docs/WindowsCE.jpg differ diff --git a/Docs/WorkItemsGroup.JPG b/Docs/WorkItemsGroup.JPG index f6d0fe1..7a44a4e 100644 Binary files a/Docs/WorkItemsGroup.JPG and b/Docs/WorkItemsGroup.JPG differ diff --git a/STPCEDemo/Form1.cs b/STPCEDemo/Form1.cs index 4f5beb0..3271c5d 100644 --- a/STPCEDemo/Form1.cs +++ b/STPCEDemo/Form1.cs @@ -42,8 +42,8 @@ namespace STPCEDemo } try { - int inUse = _stp.InUseThreads; - int inPool = _stp.ActiveThreads; + int inUse = (int)_stp.PerformanceCountersReader.InUseThreads; + int inPool = (int)_stp.PerformanceCountersReader.ActiveThreads; usageHistoryControl1.AddValues(inUse, inPool); usageControl1.Value1 = inUse; @@ -62,7 +62,7 @@ namespace STPCEDemo { int count = Convert.ToInt32(spnWorkItemsPerSecond.Value); int sleepDuration = Convert.ToInt32(spnWorkItemDuration.Value); - Debug.WriteLine(string.Format("{0}: C = {1}, S = {2}", DateTime.Now.ToString("HH:mm:ss"), count, sleepDuration)); + //Debug.WriteLine(string.Format("{0}: C = {1}, S = {2}", DateTime.Now.ToString("HH:mm:ss"), count, sleepDuration)); for (int i = 0; i < count; i++) { _stp.QueueWorkItem(DoWork, sleepDuration); @@ -78,7 +78,7 @@ namespace STPCEDemo Thread.Sleep(sleepDuration); TimeSpan duration = DateTime.Now - start; - Debug.WriteLine(string.Format("{0}: Duration = {1}", DateTime.Now.ToString("HH:mm:ss"), duration.TotalMilliseconds)); + //Debug.WriteLine(string.Format("{0}: Duration = {1}", DateTime.Now.ToString("HH:mm:ss"), duration.TotalMilliseconds)); //return null; } @@ -93,10 +93,14 @@ namespace STPCEDemo btnStartStop.Text = newRunningState ? "Stop" : "Start"; if (newRunningState) { - _stp = new SmartThreadPool( - Convert.ToInt32(spnIdleTimeout.Value) * 1000, - Convert.ToInt32(spnMaxThreads.Value), - Convert.ToInt32(spnMinThreads.Value)); + STPStartInfo stpStartInfo = new STPStartInfo() + { + IdleTimeout = Convert.ToInt32(spnIdleTimeout.Value) * 1000, + MaxWorkerThreads = Convert.ToInt32(spnMaxThreads.Value), + MinWorkerThreads = Convert.ToInt32(spnMinThreads.Value), + EnableLocalPerformanceCounters = true, + }; + _stp = new SmartThreadPool(stpStartInfo); } else { @@ -105,6 +109,9 @@ namespace STPCEDemo _stp.Shutdown(); } _stp = null; + usageHistoryControl1.Reset(); + usageControl1.Value1 = 0; + usageControl1.Value2 = 0; } spnIdleTimeout.Enabled = !newRunningState; uiTimer.Enabled = newRunningState; diff --git a/STPExamples/STPExamples.csproj b/STPExamples/STPExamples.csproj index 5070d38..57ed5e3 100644 --- a/STPExamples/STPExamples.csproj +++ b/STPExamples/STPExamples.csproj @@ -1,7 +1,7 @@  Local - 8.0.50727 + 9.0.30729 2.0 {AE943A5A-7CFD-4E0D-BA51-FB763AAEA9A3} Debug @@ -72,16 +72,6 @@ none prompt - - bin\ReleaseCE\ - TRACE - 285212672 - true - - - AnyCPU - prompt - System diff --git a/STPSLDemo/App.xaml b/STPSLDemo/App.xaml new file mode 100644 index 0000000..f971b91 --- /dev/null +++ b/STPSLDemo/App.xaml @@ -0,0 +1,7 @@ + + + + diff --git a/STPSLDemo/App.xaml.cs b/STPSLDemo/App.xaml.cs new file mode 100644 index 0000000..7996485 --- /dev/null +++ b/STPSLDemo/App.xaml.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Shapes; + +namespace STPSLDemo +{ + public partial class App : Application + { + + public App() + { + this.Startup += this.Application_Startup; + this.Exit += this.Application_Exit; + this.UnhandledException += this.Application_UnhandledException; + + InitializeComponent(); + } + + private void Application_Startup(object sender, StartupEventArgs e) + { + this.RootVisual = new Page(); + } + + private void Application_Exit(object sender, EventArgs e) + { + + } + private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) + { + // If the app is running outside of the debugger then report the exception using + // the browser's exception mechanism. On IE this will display it a yellow alert + // icon in the status bar and Firefox will display a script error. + if (!System.Diagnostics.Debugger.IsAttached) + { + + // NOTE: This will allow the application to continue running after an exception has been thrown + // but not handled. + // For production applications this error handling should be replaced with something that will + // report the error to the website and stop the application. + e.Handled = true; + Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); }); + } + } + private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e) + { + try + { + string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace; + errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n"); + + System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight 2 Application " + errorMsg + "\");"); + } + catch (Exception) + { + } + } + } +} diff --git a/STPSLDemo/Groupbox.cs b/STPSLDemo/Groupbox.cs new file mode 100644 index 0000000..7e90ec4 --- /dev/null +++ b/STPSLDemo/Groupbox.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Shapes; + +namespace STPSLDemo +{ + public class Groupbox : ContentControl + { + public Groupbox() + { + DefaultStyleKey = this.GetType(); + } + + public static readonly DependencyProperty HeaderProperty = + DependencyProperty.Register("Header", typeof(object), typeof(Groupbox), null); + + public object Header + { + get { return GetValue(HeaderProperty); } + set { SetValue(HeaderProperty, value); } + } + + public static readonly DependencyProperty HeaderTemplateProperty = + DependencyProperty.Register("HeaderTemplate", typeof(DataTemplate), typeof(Groupbox), null); + + + public DataTemplate HeaderTemplate + { + get { return (DataTemplate)GetValue(HeaderTemplateProperty); } + set { SetValue(HeaderTemplateProperty, value); } + } + } +} diff --git a/STPSLDemo/Groupbox.xaml b/STPSLDemo/Groupbox.xaml new file mode 100644 index 0000000..07e3ebd --- /dev/null +++ b/STPSLDemo/Groupbox.xaml @@ -0,0 +1,32 @@ + + + \ No newline at end of file diff --git a/STPSLDemo/Page.xaml b/STPSLDemo/Page.xaml new file mode 100644 index 0000000..1dc1fa6 --- /dev/null +++ b/STPSLDemo/Page.xaml @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +