Import OpenSimulator 0.9.3.0 baseline for NexVerse
This commit is contained in:
1 parent
55c1ea7998
commit
3655a1b0fc
2402 files changed
+636839
-162
No files matched your search
@@ -0,0 +1,14 @@
|
||||
namespace Amib.Threading.Internal
|
||||
{
|
||||
internal class CanceledWorkItemsGroup
|
||||
{
|
||||
public readonly static CanceledWorkItemsGroup NotCanceledWorkItemsGroup = new();
|
||||
|
||||
public CanceledWorkItemsGroup()
|
||||
{
|
||||
IsCanceled = false;
|
||||
}
|
||||
|
||||
public bool IsCanceled { get; set; }
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
using System;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace Amib.Threading
|
||||
{
|
||||
#region Exceptions
|
||||
|
||||
/// <summary>
|
||||
/// Represents an exception in case IWorkItemResult.GetResult has been canceled
|
||||
/// </summary>
|
||||
public sealed partial class WorkItemCancelException : Exception
|
||||
{
|
||||
public WorkItemCancelException()
|
||||
{
|
||||
}
|
||||
|
||||
public WorkItemCancelException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public WorkItemCancelException(string message, Exception e)
|
||||
: base(message, e)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents an exception in case IWorkItemResult.GetResult has been timed out
|
||||
/// </summary>
|
||||
public sealed partial class WorkItemTimeoutException : Exception
|
||||
{
|
||||
public WorkItemTimeoutException()
|
||||
{
|
||||
}
|
||||
|
||||
public WorkItemTimeoutException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public WorkItemTimeoutException(string message, Exception e)
|
||||
: base(message, e)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents an exception in case IWorkItemResult.GetResult has been timed out
|
||||
/// </summary>
|
||||
public sealed partial class WorkItemResultException : Exception
|
||||
{
|
||||
public WorkItemResultException()
|
||||
{
|
||||
}
|
||||
|
||||
public WorkItemResultException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public WorkItemResultException(string message, Exception e)
|
||||
: base(message, e)
|
||||
{
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+517
@@ -0,0 +1,517 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace Amib.Threading
|
||||
{
|
||||
#region Delegates
|
||||
|
||||
/// <summary>
|
||||
/// A delegate that represents the method to run as the work item
|
||||
/// </summary>
|
||||
/// <param name="state">A state object for the method to run</param>
|
||||
public delegate object WorkItemCallback(object state);
|
||||
|
||||
/// <summary>
|
||||
/// A delegate to call after the WorkItemCallback completed
|
||||
/// </summary>
|
||||
/// <param name="wir">The work item result object</param>
|
||||
public delegate void PostExecuteWorkItemCallback(IWorkItemResult wir);
|
||||
|
||||
/// <summary>
|
||||
/// A delegate to call after the WorkItemCallback completed
|
||||
/// </summary>
|
||||
/// <param name="wir">The work item result object</param>
|
||||
public delegate void PostExecuteWorkItemCallback<TResult>(IWorkItemResult<TResult> wir);
|
||||
|
||||
/// <summary>
|
||||
/// A delegate to call when a WorkItemsGroup becomes idle
|
||||
/// </summary>
|
||||
/// <param name="workItemsGroup">A reference to the WorkItemsGroup that became idle</param>
|
||||
public delegate void WorkItemsGroupIdleHandler(IWorkItemsGroup workItemsGroup);
|
||||
|
||||
/// <summary>
|
||||
/// A delegate to call after a thread is created, but before
|
||||
/// it's first use.
|
||||
/// </summary>
|
||||
public delegate void ThreadInitializationHandler();
|
||||
|
||||
/// <summary>
|
||||
/// A delegate to call when a thread is about to exit, after
|
||||
/// it is no longer belong to the pool.
|
||||
/// </summary>
|
||||
public delegate void ThreadTerminationHandler();
|
||||
|
||||
#endregion
|
||||
|
||||
#region IWorkItemsGroup interface
|
||||
|
||||
/// <summary>
|
||||
/// IWorkItemsGroup interface
|
||||
/// Created by SmartThreadPool.CreateWorkItemsGroup()
|
||||
/// </summary>
|
||||
public interface IWorkItemsGroup
|
||||
{
|
||||
/// <summary>
|
||||
/// Get/Set the name of the WorkItemsGroup
|
||||
/// </summary>
|
||||
string Name { get; set; }
|
||||
|
||||
int localID { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set the maximum number of workitem that execute cocurrency on the thread pool
|
||||
/// </summary>
|
||||
int Concurrency { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Get the number of work items waiting in the queue.
|
||||
/// </summary>
|
||||
int WaitingCallbacks { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Get an array with all the state objects of the currently running items.
|
||||
/// The array represents a snap shot and impact performance.
|
||||
/// </summary>
|
||||
object[] GetStates();
|
||||
|
||||
/// <summary>
|
||||
/// Get the WorkItemsGroup start information
|
||||
/// </summary>
|
||||
WIGStartInfo WIGStartInfo { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Starts to execute work items
|
||||
/// </summary>
|
||||
void Start();
|
||||
|
||||
/// <summary>
|
||||
/// Cancel all the work items.
|
||||
/// Same as Cancel(false)
|
||||
/// </summary>
|
||||
void Cancel();
|
||||
|
||||
/// <summary>
|
||||
/// Cancel all work items using thread abortion
|
||||
/// </summary>
|
||||
/// <param name="abortExecution">True to stop work items by raising ThreadAbortException</param>
|
||||
void Cancel(bool abortExecution);
|
||||
|
||||
/// <summary>
|
||||
/// Wait for all work item to complete.
|
||||
/// </summary>
|
||||
void WaitForIdle();
|
||||
|
||||
/// <summary>
|
||||
/// Wait for all work item to complete, until timeout expired
|
||||
/// </summary>
|
||||
/// <param name="timeout">How long to wait for the work items to complete</param>
|
||||
/// <returns>Returns true if work items completed within the timeout, otherwise false.</returns>
|
||||
bool WaitForIdle(TimeSpan timeout);
|
||||
|
||||
/// <summary>
|
||||
/// Wait for all work item to complete, until timeout expired
|
||||
/// </summary>
|
||||
/// <param name="millisecondsTimeout">How long to wait for the work items to complete in milliseconds</param>
|
||||
/// <returns>Returns true if work items completed within the timeout, otherwise false.</returns>
|
||||
bool WaitForIdle(int millisecondsTimeout);
|
||||
|
||||
/// <summary>
|
||||
/// IsIdle is true when there are no work items running or queued.
|
||||
/// </summary>
|
||||
bool IsIdle { get; }
|
||||
|
||||
/// <summary>
|
||||
/// This event is fired when all work items are completed.
|
||||
/// (When IsIdle changes to true)
|
||||
/// This event only work on WorkItemsGroup. On SmartThreadPool
|
||||
/// it throws the NotImplementedException.
|
||||
/// </summary>
|
||||
event WorkItemsGroupIdleHandler OnIdle;
|
||||
|
||||
#region QueueWorkItem
|
||||
|
||||
IWorkItemResult QueueWorkItem(WaitCallback callback);
|
||||
IWorkItemResult QueueWorkItem(WaitCallback callback, object state);
|
||||
IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WaitCallback callback);
|
||||
IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WaitCallback callback, object state);
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item
|
||||
/// </summary>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <returns>Returns a work item result</returns>
|
||||
IWorkItemResult QueueWorkItem(WorkItemCallback callback);
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item
|
||||
/// </summary>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <param name="state">
|
||||
/// The context object of the work item. Used for passing arguments to the work item.
|
||||
/// </param>
|
||||
/// <returns>Returns a work item result</returns>
|
||||
IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state);
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item
|
||||
/// </summary>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <param name="state">
|
||||
/// The context object of the work item. Used for passing arguments to the work item.
|
||||
/// </param>
|
||||
/// <param name="postExecuteWorkItemCallback">
|
||||
/// A delegate to call after the callback completion
|
||||
/// </param>
|
||||
/// <returns>Returns a work item result</returns>
|
||||
IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, PostExecuteWorkItemCallback postExecuteWorkItemCallback);
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item
|
||||
/// </summary>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <param name="state">
|
||||
/// The context object of the work item. Used for passing arguments to the work item.
|
||||
/// </param>
|
||||
/// <param name="postExecuteWorkItemCallback">
|
||||
/// A delegate to call after the callback completion
|
||||
/// </param>
|
||||
/// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
|
||||
/// <returns>Returns a work item result</returns>
|
||||
IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, PostExecuteWorkItemCallback postExecuteWorkItemCallback, CallToPostExecute callToPostExecute);
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item
|
||||
/// </summary>
|
||||
/// <param name="workItemInfo">Work item info</param>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <returns>Returns a work item result</returns>
|
||||
IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback);
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item
|
||||
/// </summary>
|
||||
/// <param name="workItemInfo">Work item information</param>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <param name="state">
|
||||
/// The context object of the work item. Used for passing arguments to the work item.
|
||||
/// </param>
|
||||
/// <returns>Returns a work item result</returns>
|
||||
IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback, object state);
|
||||
|
||||
#endregion
|
||||
|
||||
#region QueueWorkItem(Action<...>)
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item.
|
||||
/// </summary>
|
||||
/// <returns>Returns a IWorkItemResult object, but its GetResult() will always return null</returns>
|
||||
IWorkItemResult QueueWorkItem(Action action);
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item.
|
||||
/// </summary>
|
||||
/// <returns>Returns a IWorkItemResult object, but its GetResult() will always return null</returns>
|
||||
IWorkItemResult QueueWorkItem<T>(Action<T> action, T arg);
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item.
|
||||
/// </summary>
|
||||
/// <returns>Returns a IWorkItemResult object, but its GetResult() will always return null</returns>
|
||||
IWorkItemResult QueueWorkItem<T1, T2>(Action<T1, T2> action, T1 arg1, T2 arg2);
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item.
|
||||
/// </summary>
|
||||
/// <returns>Returns a IWorkItemResult object, but its GetResult() will always return null</returns>
|
||||
IWorkItemResult QueueWorkItem<T1, T2, T3>(Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3);
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item.
|
||||
/// </summary>
|
||||
/// <returns>Returns a IWorkItemResult object, but its GetResult() will always return null</returns>
|
||||
IWorkItemResult QueueWorkItem<T1, T2, T3, T4>(Action<T1, T2, T3, T4> action, T1 arg1, T2 arg2, T3 arg3, T4 arg4);
|
||||
|
||||
#endregion
|
||||
|
||||
#region QueueWorkItem(Func<...>)
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item.
|
||||
/// </summary>
|
||||
/// <returns>Returns a IWorkItemResult<TResult> object.
|
||||
/// its GetResult() returns a TResult object</returns>
|
||||
IWorkItemResult<TResult> QueueWorkItem<TResult>(Func<TResult> func);
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item.
|
||||
/// </summary>
|
||||
/// <returns>Returns a IWorkItemResult<TResult> object.
|
||||
/// its GetResult() returns a TResult object</returns>
|
||||
IWorkItemResult<TResult> QueueWorkItem<T, TResult>(Func<T, TResult> func, T arg);
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item.
|
||||
/// </summary>
|
||||
/// <returns>Returns a IWorkItemResult<TResult> object.
|
||||
/// its GetResult() returns a TResult object</returns>
|
||||
IWorkItemResult<TResult> QueueWorkItem<T1, T2, TResult>(Func<T1, T2, TResult> func, T1 arg1, T2 arg2);
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item.
|
||||
/// </summary>
|
||||
/// <returns>Returns a IWorkItemResult<TResult> object.
|
||||
/// its GetResult() returns a TResult object</returns>
|
||||
IWorkItemResult<TResult> QueueWorkItem<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult> func, T1 arg1, T2 arg2, T3 arg3);
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item.
|
||||
/// </summary>
|
||||
/// <returns>Returns a IWorkItemResult<TResult> object.
|
||||
/// its GetResult() returns a TResult object</returns>
|
||||
IWorkItemResult<TResult> QueueWorkItem<T1, T2, T3, T4, TResult>(Func<T1, T2, T3, T4, TResult> func, T1 arg1, T2 arg2, T3 arg3, T4 arg4);
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region CallToPostExecute enumerator
|
||||
|
||||
[Flags]
|
||||
public enum CallToPostExecute
|
||||
{
|
||||
/// <summary>
|
||||
/// Never call to the PostExecute call back
|
||||
/// </summary>
|
||||
Never = 0x00,
|
||||
|
||||
/// <summary>
|
||||
/// Call to the PostExecute only when the work item is cancelled
|
||||
/// </summary>
|
||||
WhenWorkItemCanceled = 0x01,
|
||||
|
||||
/// <summary>
|
||||
/// Call to the PostExecute only when the work item is not cancelled
|
||||
/// </summary>
|
||||
WhenWorkItemNotCanceled = 0x02,
|
||||
|
||||
/// <summary>
|
||||
/// Always call to the PostExecute
|
||||
/// </summary>
|
||||
Always = WhenWorkItemCanceled | WhenWorkItemNotCanceled,
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IWorkItemResult interface
|
||||
|
||||
/// <summary>
|
||||
/// The common interface of IWorkItemResult and IWorkItemResult<T>
|
||||
/// </summary>
|
||||
public interface IWaitableResult
|
||||
{
|
||||
/// <summary>
|
||||
/// This method intent is for internal use.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
IWorkItemResult GetWorkItemResult();
|
||||
|
||||
/// <summary>
|
||||
/// This method intent is for internal use.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
IWorkItemResult<TResult> GetWorkItemResultT<TResult>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// IWorkItemResult interface.
|
||||
/// Created when a WorkItemCallback work item is queued.
|
||||
/// </summary>
|
||||
public interface IWorkItemResult : IWorkItemResult<object>
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// IWorkItemResult<TResult> interface.
|
||||
/// Created when a Func<TResult> work item is queued.
|
||||
/// </summary>
|
||||
public interface IWorkItemResult<TResult> : IWaitableResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Get the result of the work item.
|
||||
/// If the work item didn't run yet then the caller waits.
|
||||
/// </summary>
|
||||
/// <returns>The result of the work item</returns>
|
||||
TResult GetResult();
|
||||
|
||||
/// <summary>
|
||||
/// Get the result of the work item.
|
||||
/// If the work item didn't run yet then the caller waits until timeout.
|
||||
/// </summary>
|
||||
/// <returns>The result of the work item</returns>
|
||||
/// On timeout throws WorkItemTimeoutException
|
||||
TResult GetResult(
|
||||
int millisecondsTimeout,
|
||||
bool exitContext);
|
||||
|
||||
/// <summary>
|
||||
/// Get the result of the work item.
|
||||
/// If the work item didn't run yet then the caller waits until timeout.
|
||||
/// </summary>
|
||||
/// <returns>The result of the work item</returns>
|
||||
/// On timeout throws WorkItemTimeoutException
|
||||
TResult GetResult(
|
||||
TimeSpan timeout,
|
||||
bool exitContext);
|
||||
|
||||
/// <summary>
|
||||
/// Get the result of the work item.
|
||||
/// If the work item didn't run yet then the caller waits until timeout or until the cancelWaitHandle is signaled.
|
||||
/// </summary>
|
||||
/// <param name="millisecondsTimeout">Timeout in milliseconds, or -1 for infinite</param>
|
||||
/// <param name="exitContext">
|
||||
/// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
|
||||
/// </param>
|
||||
/// <param name="cancelWaitHandle">A cancel wait handle to interrupt the blocking if needed</param>
|
||||
/// <returns>The result of the work item</returns>
|
||||
/// On timeout throws WorkItemTimeoutException
|
||||
/// On cancel throws WorkItemCancelException
|
||||
TResult GetResult(
|
||||
int millisecondsTimeout,
|
||||
bool exitContext,
|
||||
WaitHandle cancelWaitHandle);
|
||||
|
||||
/// <summary>
|
||||
/// Get the result of the work item.
|
||||
/// If the work item didn't run yet then the caller waits until timeout or until the cancelWaitHandle is signaled.
|
||||
/// </summary>
|
||||
/// <returns>The result of the work item</returns>
|
||||
/// On timeout throws WorkItemTimeoutException
|
||||
/// On cancel throws WorkItemCancelException
|
||||
TResult GetResult(
|
||||
TimeSpan timeout,
|
||||
bool exitContext,
|
||||
WaitHandle cancelWaitHandle);
|
||||
|
||||
/// <summary>
|
||||
/// Get the result of the work item.
|
||||
/// If the work item didn't run yet then the caller waits.
|
||||
/// </summary>
|
||||
/// <param name="e">Filled with the exception if one was thrown</param>
|
||||
/// <returns>The result of the work item</returns>
|
||||
TResult GetResult(out Exception e);
|
||||
|
||||
/// <summary>
|
||||
/// Get the result of the work item.
|
||||
/// If the work item didn't run yet then the caller waits until timeout.
|
||||
/// </summary>
|
||||
/// <param name="millisecondsTimeout"></param>
|
||||
/// <param name="exitContext"></param>
|
||||
/// <param name="e">Filled with the exception if one was thrown</param>
|
||||
/// <returns>The result of the work item</returns>
|
||||
/// On timeout throws WorkItemTimeoutException
|
||||
TResult GetResult(
|
||||
int millisecondsTimeout,
|
||||
bool exitContext,
|
||||
out Exception e);
|
||||
|
||||
/// <summary>
|
||||
/// Get the result of the work item.
|
||||
/// If the work item didn't run yet then the caller waits until timeout.
|
||||
/// </summary>
|
||||
/// <param name="exitContext"></param>
|
||||
/// <param name="e">Filled with the exception if one was thrown</param>
|
||||
/// <param name="timeout"></param>
|
||||
/// <returns>The result of the work item</returns>
|
||||
/// On timeout throws WorkItemTimeoutException
|
||||
TResult GetResult(
|
||||
TimeSpan timeout,
|
||||
bool exitContext,
|
||||
out Exception e);
|
||||
|
||||
/// <summary>
|
||||
/// Get the result of the work item.
|
||||
/// If the work item didn't run yet then the caller waits until timeout or until the cancelWaitHandle is signaled.
|
||||
/// </summary>
|
||||
/// <param name="millisecondsTimeout">Timeout in milliseconds, or -1 for infinite</param>
|
||||
/// <param name="exitContext">
|
||||
/// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
|
||||
/// </param>
|
||||
/// <param name="cancelWaitHandle">A cancel wait handle to interrupt the blocking if needed</param>
|
||||
/// <param name="e">Filled with the exception if one was thrown</param>
|
||||
/// <returns>The result of the work item</returns>
|
||||
/// On timeout throws WorkItemTimeoutException
|
||||
/// On cancel throws WorkItemCancelException
|
||||
TResult GetResult(
|
||||
int millisecondsTimeout,
|
||||
bool exitContext,
|
||||
WaitHandle cancelWaitHandle,
|
||||
out Exception e);
|
||||
|
||||
/// <summary>
|
||||
/// Get the result of the work item.
|
||||
/// If the work item didn't run yet then the caller waits until timeout or until the cancelWaitHandle is signaled.
|
||||
/// </summary>
|
||||
/// <returns>The result of the work item</returns>
|
||||
/// <param name="cancelWaitHandle"></param>
|
||||
/// <param name="e">Filled with the exception if one was thrown</param>
|
||||
/// <param name="timeout"></param>
|
||||
/// <param name="exitContext"></param>
|
||||
/// On timeout throws WorkItemTimeoutException
|
||||
/// On cancel throws WorkItemCancelException
|
||||
TResult GetResult(
|
||||
TimeSpan timeout,
|
||||
bool exitContext,
|
||||
WaitHandle cancelWaitHandle,
|
||||
out Exception e);
|
||||
|
||||
/// <summary>
|
||||
/// Gets an indication whether the asynchronous operation has completed.
|
||||
/// </summary>
|
||||
bool IsCompleted { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets an indication whether the asynchronous operation has been canceled.
|
||||
/// </summary>
|
||||
bool IsCanceled { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user-defined object that contains context data
|
||||
/// for the work item method.
|
||||
/// </summary>
|
||||
object State { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Same as Cancel(false).
|
||||
/// </summary>
|
||||
bool Cancel();
|
||||
|
||||
/// <summary>
|
||||
/// Cancel the work item execution.
|
||||
/// If the work item is in the queue then it won't execute
|
||||
/// If the work item is completed, it will remain completed
|
||||
/// If the work item is in progress then the user can check the SmartThreadPool.IsWorkItemCanceled
|
||||
/// property to check if the work item has been cancelled. If the abortExecution is set to true then
|
||||
/// the Smart Thread Pool will send an AbortException to the running thread to stop the execution
|
||||
/// of the work item. When an in progress work item is canceled its GetResult will throw WorkItemCancelException.
|
||||
/// If the work item is already cancelled it will remain cancelled
|
||||
/// </summary>
|
||||
/// <param name="abortExecution">When true send an AbortException to the executing thread.</param>
|
||||
/// <returns>Returns true if the work item was not completed, otherwise false.</returns>
|
||||
bool Cancel(bool abortExecution);
|
||||
|
||||
/// <summary>
|
||||
/// Return the result, same as GetResult()
|
||||
/// </summary>
|
||||
TResult Result { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns the exception if occured otherwise returns null.
|
||||
/// </summary>
|
||||
object Exception { get; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
|
||||
namespace Amib.Threading.Internal
|
||||
{
|
||||
/// <summary>
|
||||
/// An internal delegate to call when the WorkItem starts or completes
|
||||
/// </summary>
|
||||
internal delegate void WorkItemStateCallback(WorkItem workItem);
|
||||
|
||||
internal interface IInternalWorkItemResult
|
||||
{
|
||||
event WorkItemStateCallback OnWorkItemStarted;
|
||||
event WorkItemStateCallback OnWorkItemCompleted;
|
||||
}
|
||||
|
||||
internal interface IInternalWaitableResult
|
||||
{
|
||||
/// <summary>
|
||||
/// This method is intent for internal use.
|
||||
/// </summary>
|
||||
IWorkItemResult GetWorkItemResult();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
[assembly: AssemblyTitle("Amib.Threading")]
|
||||
[assembly: AssemblyDescription("Smart Thread Pool")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("Amib.Threading")]
|
||||
[assembly: AssemblyCopyright("")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
[assembly: ComVisible(false)]
|
||||
[assembly: Guid("c764a3de-c4f8-434d-85b5-a09830d1e44f")]
|
||||
[assembly: AssemblyVersion("2.2.3.0")]
|
||||
|
||||
#if (_PUBLISH)
|
||||
[assembly: InternalsVisibleTo("STPTests,PublicKey=00240000048000009400000006020000002400005253413100040000010001004fe3d39add741ba7c8d52cd1eb0d94c7d79060ad956cbaff0e51c1dce94db10356b261778bc1ac3114b3218434da6fcd8416dd5507653809598f7d2afc422099ce4f6b7b0477f18e6c57c727ef2a7ab6ee56e6b4589fe44cb0e25f2875a3c65ab0383ee33c4dd93023f7ce1218bebc8b7a9a1dac878938f5c4f45ea74b6bd8ad")]
|
||||
#else
|
||||
[assembly: InternalsVisibleTo("STPTests")]
|
||||
#endif
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace Amib.Threading.Internal
|
||||
{
|
||||
internal static class STPEventWaitHandle
|
||||
{
|
||||
public const int WaitTimeout = Timeout.Infinite;
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
|
||||
{
|
||||
return WaitHandle.WaitAll(waitHandles, millisecondsTimeout, exitContext);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static int WaitAny(WaitHandle[] waitHandles)
|
||||
{
|
||||
return WaitHandle.WaitAny(waitHandles);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
|
||||
{
|
||||
return WaitHandle.WaitAny(waitHandles, millisecondsTimeout, exitContext);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static bool WaitOne(WaitHandle waitHandle, int millisecondsTimeout, bool exitContext)
|
||||
{
|
||||
return waitHandle.WaitOne(millisecondsTimeout, exitContext);
|
||||
}
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace Amib.Threading
|
||||
{
|
||||
/// <summary>
|
||||
/// Summary description for STPStartInfo.
|
||||
/// </summary>
|
||||
public class STPStartInfo : WIGStartInfo
|
||||
{
|
||||
private int _idleTimeout = SmartThreadPool.DefaultIdleTimeout;
|
||||
private int _minWorkerThreads = SmartThreadPool.DefaultMinWorkerThreads;
|
||||
private int _maxWorkerThreads = SmartThreadPool.DefaultMaxWorkerThreads;
|
||||
private ThreadPriority _threadPriority = SmartThreadPool.DefaultThreadPriority;
|
||||
private bool _areThreadsBackground = SmartThreadPool.DefaultAreThreadsBackground;
|
||||
private string _threadPoolName = SmartThreadPool.DefaultThreadPoolName;
|
||||
private int? _maxStackSize = SmartThreadPool.DefaultMaxStackSize;
|
||||
private bool _supressflow = false;
|
||||
|
||||
public STPStartInfo()
|
||||
{
|
||||
_threadPriority = SmartThreadPool.DefaultThreadPriority;
|
||||
_maxWorkerThreads = SmartThreadPool.DefaultMaxWorkerThreads;
|
||||
_idleTimeout = SmartThreadPool.DefaultIdleTimeout;
|
||||
_minWorkerThreads = SmartThreadPool.DefaultMinWorkerThreads;
|
||||
}
|
||||
|
||||
public STPStartInfo(STPStartInfo stpStartInfo)
|
||||
: base(stpStartInfo)
|
||||
{
|
||||
_idleTimeout = stpStartInfo.IdleTimeout;
|
||||
_minWorkerThreads = stpStartInfo.MinWorkerThreads;
|
||||
_maxWorkerThreads = stpStartInfo.MaxWorkerThreads;
|
||||
_threadPriority = stpStartInfo.ThreadPriority;
|
||||
_threadPoolName = stpStartInfo._threadPoolName;
|
||||
_areThreadsBackground = stpStartInfo.AreThreadsBackground;
|
||||
_apartmentState = stpStartInfo._apartmentState;
|
||||
_supressflow = stpStartInfo._supressflow;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set the idle timeout in milliseconds.
|
||||
/// If a thread is idle (starved) longer than IdleTimeout then it may quit.
|
||||
/// </summary>
|
||||
public virtual int IdleTimeout
|
||||
{
|
||||
get { return _idleTimeout; }
|
||||
set
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
_idleTimeout = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set the lower limit of threads in the pool.
|
||||
/// </summary>
|
||||
public virtual int MinWorkerThreads
|
||||
{
|
||||
get { return _minWorkerThreads; }
|
||||
set
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
_minWorkerThreads = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set the upper limit of threads in the pool.
|
||||
/// </summary>
|
||||
public virtual int MaxWorkerThreads
|
||||
{
|
||||
get { return _maxWorkerThreads; }
|
||||
set
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
_maxWorkerThreads = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set the scheduling priority of the threads in the pool.
|
||||
/// The Os handles the scheduling.
|
||||
/// </summary>
|
||||
public virtual ThreadPriority ThreadPriority
|
||||
{
|
||||
get { return _threadPriority; }
|
||||
set
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
_threadPriority = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set the thread pool name. Threads will get names depending on this.
|
||||
/// </summary>
|
||||
public virtual string ThreadPoolName
|
||||
{
|
||||
get { return _threadPoolName; }
|
||||
set
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
_threadPoolName = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set backgroundness of thread in thread pool.
|
||||
/// </summary>
|
||||
public virtual bool AreThreadsBackground
|
||||
{
|
||||
get { return _areThreadsBackground; }
|
||||
set
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
_areThreadsBackground = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get a readonly version of this STPStartInfo.
|
||||
/// </summary>
|
||||
/// <returns>Returns a readonly reference to this STPStartInfo</returns>
|
||||
public new STPStartInfo AsReadOnly()
|
||||
{
|
||||
return new STPStartInfo(this) { _readOnly = true };
|
||||
}
|
||||
|
||||
private ApartmentState _apartmentState = SmartThreadPool.DefaultApartmentState;
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set the apartment state of threads in the thread pool
|
||||
/// </summary>
|
||||
public ApartmentState ApartmentState
|
||||
{
|
||||
get { return _apartmentState; }
|
||||
set
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
_apartmentState = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set the max stack size of threads in the thread pool
|
||||
/// </summary>
|
||||
public int? MaxStackSize
|
||||
{
|
||||
get { return _maxStackSize; }
|
||||
set
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
if (value.HasValue && value.Value < 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException("value", "Value must be greater than 0.");
|
||||
}
|
||||
_maxStackSize = value;
|
||||
}
|
||||
}
|
||||
|
||||
public bool SuppressFlow
|
||||
{
|
||||
get { return _supressflow; }
|
||||
set
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
_supressflow = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
|
||||
using Amib.Threading.Internal;
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace Amib.Threading
|
||||
{
|
||||
public partial class SmartThreadPool
|
||||
{
|
||||
#region ThreadEntry class
|
||||
|
||||
internal class ThreadEntry
|
||||
{
|
||||
/// <summary>
|
||||
/// The thread creation time
|
||||
/// The value is stored as UTC value.
|
||||
/// </summary>
|
||||
private readonly DateTime _creationTime;
|
||||
|
||||
/// <summary>
|
||||
/// The last time this thread has been running
|
||||
/// It is updated by IAmAlive() method
|
||||
/// The value is stored as UTC value.
|
||||
/// </summary>
|
||||
private DateTime _lastAliveTime;
|
||||
|
||||
/// <summary>
|
||||
/// A reference from each thread in the thread pool to its SmartThreadPool
|
||||
/// object container.
|
||||
/// With this variable a thread can know whatever it belongs to a
|
||||
/// SmartThreadPool.
|
||||
/// </summary>
|
||||
private SmartThreadPool _associatedSmartThreadPool;
|
||||
|
||||
/// <summary>
|
||||
/// A reference to the current work item a thread from the thread pool
|
||||
/// is executing.
|
||||
/// </summary>
|
||||
public WorkItem CurrentWorkItem { get; set; }
|
||||
public Thread WorkThread;
|
||||
|
||||
public ThreadEntry(SmartThreadPool stp, Thread th)
|
||||
{
|
||||
_associatedSmartThreadPool = stp;
|
||||
_creationTime = DateTime.UtcNow;
|
||||
_lastAliveTime = DateTime.MinValue;
|
||||
WorkThread = th;
|
||||
}
|
||||
|
||||
public SmartThreadPool AssociatedSmartThreadPool
|
||||
{
|
||||
get { return _associatedSmartThreadPool; }
|
||||
}
|
||||
|
||||
public void IAmAlive()
|
||||
{
|
||||
_lastAliveTime = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
public void Clean()
|
||||
{
|
||||
WorkThread = null;
|
||||
_associatedSmartThreadPool = null;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+1528
File diff suppressed because it is too large.
Load diff
+141
@@ -0,0 +1,141 @@
|
||||
using System;
|
||||
|
||||
namespace Amib.Threading
|
||||
{
|
||||
/// <summary>
|
||||
/// Summary description for WIGStartInfo.
|
||||
/// </summary>
|
||||
public class WIGStartInfo
|
||||
{
|
||||
private bool _useCallerCallContext;
|
||||
private bool _disposeOfStateObjects;
|
||||
private CallToPostExecute _callToPostExecute;
|
||||
private PostExecuteWorkItemCallback _postExecuteWorkItemCallback;
|
||||
private bool _startSuspended;
|
||||
private bool _fillStateWithArgs;
|
||||
|
||||
protected bool _readOnly;
|
||||
|
||||
public WIGStartInfo()
|
||||
{
|
||||
_fillStateWithArgs = SmartThreadPool.DefaultFillStateWithArgs;
|
||||
_startSuspended = SmartThreadPool.DefaultStartSuspended;
|
||||
_postExecuteWorkItemCallback = SmartThreadPool.DefaultPostExecuteWorkItemCallback;
|
||||
_callToPostExecute = SmartThreadPool.DefaultCallToPostExecute;
|
||||
_disposeOfStateObjects = SmartThreadPool.DefaultDisposeOfStateObjects;
|
||||
_useCallerCallContext = SmartThreadPool.DefaultUseCallerCallContext;
|
||||
}
|
||||
|
||||
public WIGStartInfo(WIGStartInfo wigStartInfo)
|
||||
{
|
||||
_useCallerCallContext = wigStartInfo.UseCallerCallContext;
|
||||
_disposeOfStateObjects = wigStartInfo.DisposeOfStateObjects;
|
||||
_callToPostExecute = wigStartInfo.CallToPostExecute;
|
||||
_postExecuteWorkItemCallback = wigStartInfo.PostExecuteWorkItemCallback;
|
||||
_startSuspended = wigStartInfo.StartSuspended;
|
||||
_fillStateWithArgs = wigStartInfo.FillStateWithArgs;
|
||||
}
|
||||
|
||||
protected void ThrowIfReadOnly()
|
||||
{
|
||||
if (_readOnly)
|
||||
{
|
||||
throw new NotSupportedException("This is a readonly instance and set is not supported");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set if to use the caller's security context
|
||||
/// </summary>
|
||||
public virtual bool UseCallerCallContext
|
||||
{
|
||||
get { return _useCallerCallContext; }
|
||||
set
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
_useCallerCallContext = value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set if to dispose of the state object of a work item
|
||||
/// </summary>
|
||||
public virtual bool DisposeOfStateObjects
|
||||
{
|
||||
get { return _disposeOfStateObjects; }
|
||||
set
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
_disposeOfStateObjects = value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set the run the post execute options
|
||||
/// </summary>
|
||||
public virtual CallToPostExecute CallToPostExecute
|
||||
{
|
||||
get { return _callToPostExecute; }
|
||||
set
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
_callToPostExecute = value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set the default post execute callback
|
||||
/// </summary>
|
||||
public virtual PostExecuteWorkItemCallback PostExecuteWorkItemCallback
|
||||
{
|
||||
get { return _postExecuteWorkItemCallback; }
|
||||
set
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
_postExecuteWorkItemCallback = value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set if the work items execution should be suspended until the Start()
|
||||
/// method is called.
|
||||
/// </summary>
|
||||
public virtual bool StartSuspended
|
||||
{
|
||||
get { return _startSuspended; }
|
||||
set
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
_startSuspended = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set the if QueueWorkItem of Action<...>/Func<...> fill the
|
||||
/// arguments as an object array into the state of the work item.
|
||||
/// The arguments can be access later by IWorkItemResult.State.
|
||||
/// </summary>
|
||||
public virtual bool FillStateWithArgs
|
||||
{
|
||||
get { return _fillStateWithArgs; }
|
||||
set
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
_fillStateWithArgs = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get a readonly version of this WIGStartInfo
|
||||
/// </summary>
|
||||
/// <returns>Returns a readonly reference to this WIGStartInfoRO</returns>
|
||||
public WIGStartInfo AsReadOnly()
|
||||
{
|
||||
return new WIGStartInfo(this) { _readOnly = true };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace Amib.Threading.Internal
|
||||
{
|
||||
public partial class WorkItem
|
||||
{
|
||||
#region WorkItemResult class
|
||||
|
||||
private class WorkItemResult : IWorkItemResult, IInternalWorkItemResult, IInternalWaitableResult
|
||||
{
|
||||
/// <summary>
|
||||
/// A back reference to the work item
|
||||
/// </summary>
|
||||
private readonly WorkItem _workItem;
|
||||
|
||||
public WorkItemResult(WorkItem workItem)
|
||||
{
|
||||
_workItem = workItem;
|
||||
}
|
||||
|
||||
internal WorkItem GetWorkItem()
|
||||
{
|
||||
return _workItem;
|
||||
}
|
||||
|
||||
#region IWorkItemResult Members
|
||||
|
||||
public bool IsCompleted
|
||||
{
|
||||
get
|
||||
{
|
||||
return _workItem.IsCompleted;
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsCanceled
|
||||
{
|
||||
get
|
||||
{
|
||||
return _workItem.IsCanceled;
|
||||
}
|
||||
}
|
||||
|
||||
public object GetResult()
|
||||
{
|
||||
return _workItem.GetResult(Timeout.Infinite, true, null);
|
||||
}
|
||||
|
||||
public object GetResult(int millisecondsTimeout, bool exitContext)
|
||||
{
|
||||
return _workItem.GetResult(millisecondsTimeout, exitContext, null);
|
||||
}
|
||||
|
||||
public object GetResult(TimeSpan timeout, bool exitContext)
|
||||
{
|
||||
return _workItem.GetResult((int)timeout.TotalMilliseconds, exitContext, null);
|
||||
}
|
||||
|
||||
public object GetResult(int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle)
|
||||
{
|
||||
return _workItem.GetResult(millisecondsTimeout, exitContext, cancelWaitHandle);
|
||||
}
|
||||
|
||||
public object GetResult(TimeSpan timeout, bool exitContext, WaitHandle cancelWaitHandle)
|
||||
{
|
||||
return _workItem.GetResult((int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle);
|
||||
}
|
||||
|
||||
public object GetResult(out Exception e)
|
||||
{
|
||||
return _workItem.GetResult(Timeout.Infinite, true, null, out e);
|
||||
}
|
||||
|
||||
public object GetResult(int millisecondsTimeout, bool exitContext, out Exception e)
|
||||
{
|
||||
return _workItem.GetResult(millisecondsTimeout, exitContext, null, out e);
|
||||
}
|
||||
|
||||
public object GetResult(TimeSpan timeout, bool exitContext, out Exception e)
|
||||
{
|
||||
return _workItem.GetResult((int)timeout.TotalMilliseconds, exitContext, null, out e);
|
||||
}
|
||||
|
||||
public object GetResult(int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e)
|
||||
{
|
||||
return _workItem.GetResult(millisecondsTimeout, exitContext, cancelWaitHandle, out e);
|
||||
}
|
||||
|
||||
public object GetResult(TimeSpan timeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e)
|
||||
{
|
||||
return _workItem.GetResult((int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle, out e);
|
||||
}
|
||||
|
||||
public bool Cancel()
|
||||
{
|
||||
return Cancel(false);
|
||||
}
|
||||
|
||||
public bool Cancel(bool abortExecution)
|
||||
{
|
||||
return _workItem.Cancel(abortExecution);
|
||||
}
|
||||
|
||||
public object State
|
||||
{
|
||||
get
|
||||
{
|
||||
return _workItem.m_state;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return the result, same as GetResult()
|
||||
/// </summary>
|
||||
public object Result
|
||||
{
|
||||
get { return GetResult(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the exception if occured otherwise returns null.
|
||||
/// This value is valid only after the work item completed,
|
||||
/// before that it is always null.
|
||||
/// </summary>
|
||||
public object Exception
|
||||
{
|
||||
get { return _workItem.m_exception; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IInternalWorkItemResult Members
|
||||
|
||||
public event WorkItemStateCallback OnWorkItemStarted
|
||||
{
|
||||
add
|
||||
{
|
||||
_workItem.OnWorkItemStarted += value;
|
||||
}
|
||||
remove
|
||||
{
|
||||
_workItem.OnWorkItemStarted -= value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public event WorkItemStateCallback OnWorkItemCompleted
|
||||
{
|
||||
add
|
||||
{
|
||||
_workItem.OnWorkItemCompleted += value;
|
||||
}
|
||||
remove
|
||||
{
|
||||
_workItem.OnWorkItemCompleted -= value;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IInternalWorkItemResult Members
|
||||
|
||||
public IWorkItemResult GetWorkItemResult()
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
public IWorkItemResult<TResult> GetWorkItemResultT<TResult>()
|
||||
{
|
||||
return new WorkItemResultTWrapper<TResult>(this);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
}
|
||||
+974
@@ -0,0 +1,974 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
|
||||
namespace Amib.Threading.Internal
|
||||
{
|
||||
/// <summary>
|
||||
/// Holds a callback delegate and the state for that delegate.
|
||||
/// </summary>
|
||||
public partial class WorkItem
|
||||
{
|
||||
#region WorkItemState enum
|
||||
|
||||
/// <summary>
|
||||
/// Indicates the state of the work item in the thread pool
|
||||
/// </summary>
|
||||
private enum WorkItemState
|
||||
{
|
||||
InQueue = 0, // Nexts: InProgress, Canceled
|
||||
InProgress = 1, // Nexts: Completed, Canceled
|
||||
Completed = 2, // Stays Completed
|
||||
Canceled = 3, // Stays Canceled
|
||||
}
|
||||
|
||||
private static bool IsValidStatesTransition(WorkItemState currentState, WorkItemState nextState)
|
||||
{
|
||||
bool valid = false;
|
||||
|
||||
switch (currentState)
|
||||
{
|
||||
case WorkItemState.InQueue:
|
||||
valid = (WorkItemState.InProgress == nextState) || (WorkItemState.Canceled == nextState);
|
||||
break;
|
||||
case WorkItemState.InProgress:
|
||||
valid = (WorkItemState.Completed == nextState) || (WorkItemState.Canceled == nextState);
|
||||
break;
|
||||
case WorkItemState.Completed:
|
||||
case WorkItemState.Canceled:
|
||||
// Cannot be changed
|
||||
break;
|
||||
default:
|
||||
// Unknown state
|
||||
Debug.Assert(false);
|
||||
break;
|
||||
}
|
||||
|
||||
return valid;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Fields
|
||||
|
||||
/// <summary>
|
||||
/// Callback delegate for the callback.
|
||||
/// </summary>
|
||||
private WorkItemCallback m_callback;
|
||||
private WaitCallback m_callbackNoResult;
|
||||
|
||||
/// <summary>
|
||||
/// State with which to call the callback delegate.
|
||||
/// </summary>
|
||||
private object m_state;
|
||||
|
||||
/// <summary>
|
||||
/// Stores the caller's context
|
||||
/// </summary>
|
||||
private ExecutionContext m_callerContext = null;
|
||||
|
||||
/// <summary>
|
||||
/// Holds the result of the mehtod
|
||||
/// </summary>
|
||||
private object m_result;
|
||||
|
||||
/// <summary>
|
||||
/// Hold the exception if the method threw it
|
||||
/// </summary>
|
||||
private Exception m_exception;
|
||||
|
||||
/// <summary>
|
||||
/// Hold the state of the work item
|
||||
/// </summary>
|
||||
private WorkItemState m_workItemState;
|
||||
|
||||
/// <summary>
|
||||
/// A ManualResetEvent to indicate that the result is ready
|
||||
/// </summary>
|
||||
private ManualResetEvent m_workItemCompleted;
|
||||
|
||||
/// <summary>
|
||||
/// A reference count to the _workItemCompleted.
|
||||
/// When it reaches to zero _workItemCompleted is Closed
|
||||
/// </summary>
|
||||
private int m_workItemCompletedRefCount;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the result state of the work item
|
||||
/// </summary>
|
||||
private readonly WorkItemResult m_workItemResult;
|
||||
|
||||
/// <summary>
|
||||
/// Work item info
|
||||
/// </summary>
|
||||
private readonly WorkItemInfo m_workItemInfo;
|
||||
|
||||
/// <summary>
|
||||
/// Called when the WorkItem starts
|
||||
/// </summary>
|
||||
private event WorkItemStateCallback m_workItemStartedEvent;
|
||||
|
||||
/// <summary>
|
||||
/// Called when the WorkItem completes
|
||||
/// </summary>
|
||||
private event WorkItemStateCallback m_workItemCompletedEvent;
|
||||
|
||||
/// <summary>
|
||||
/// A reference to an object that indicates whatever the
|
||||
/// WorkItemsGroup has been canceled
|
||||
/// </summary>
|
||||
private CanceledWorkItemsGroup m_canceledWorkItemsGroup = CanceledWorkItemsGroup.NotCanceledWorkItemsGroup;
|
||||
|
||||
/// <summary>
|
||||
/// A reference to an object that indicates whatever the
|
||||
/// SmartThreadPool has been canceled
|
||||
/// </summary>
|
||||
private CanceledWorkItemsGroup m_canceledSmartThreadPool = CanceledWorkItemsGroup.NotCanceledWorkItemsGroup;
|
||||
|
||||
/// <summary>
|
||||
/// The work item group this work item belong to.
|
||||
/// </summary>
|
||||
private readonly IWorkItemsGroup m_workItemsGroup;
|
||||
|
||||
/// <summary>
|
||||
/// The thread that executes this workitem.
|
||||
/// This field is available for the period when the work item is executed, before and after it is null.
|
||||
/// </summary>
|
||||
private Thread m_executingThread;
|
||||
|
||||
/// <summary>
|
||||
/// The absulote time when the work item will be timeout
|
||||
/// </summary>
|
||||
private long m_expirationTime;
|
||||
|
||||
#region Performance Counter fields
|
||||
|
||||
/// <summary>
|
||||
/// Stores how long the work item waited on the stp queue
|
||||
/// </summary>
|
||||
private Stopwatch _waitingOnQueueStopwatch;
|
||||
|
||||
/// <summary>
|
||||
/// Stores how much time it took the work item to execute after it went out of the queue
|
||||
/// </summary>
|
||||
private Stopwatch _processingStopwatch;
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
|
||||
#region Properties
|
||||
|
||||
public TimeSpan WaitingTime
|
||||
{
|
||||
get
|
||||
{
|
||||
return _waitingOnQueueStopwatch.Elapsed;
|
||||
}
|
||||
}
|
||||
|
||||
public TimeSpan ProcessTime
|
||||
{
|
||||
get
|
||||
{
|
||||
return _processingStopwatch.Elapsed;
|
||||
}
|
||||
}
|
||||
|
||||
internal WorkItemInfo WorkItemInfo
|
||||
{
|
||||
get
|
||||
{
|
||||
return m_workItemInfo;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Construction
|
||||
|
||||
/// <summary>
|
||||
/// Initialize the callback holding object.
|
||||
/// </summary>
|
||||
/// <param name="workItemsGroup">The workItemGroup of the workitem</param>
|
||||
/// <param name="workItemInfo">The WorkItemInfo of te workitem</param>
|
||||
/// <param name="callback">Callback delegate for the callback.</param>
|
||||
/// <param name="state">State with which to call the callback delegate.</param>
|
||||
///
|
||||
/// We assume that the WorkItem object is created within the thread
|
||||
/// that meant to run the callback
|
||||
public WorkItem(IWorkItemsGroup workItemsGroup, WorkItemInfo workItemInfo, WorkItemCallback callback, object state)
|
||||
{
|
||||
m_workItemsGroup = workItemsGroup;
|
||||
m_workItemInfo = workItemInfo;
|
||||
|
||||
if (m_workItemInfo.UseCallerCallContext && !ExecutionContext.IsFlowSuppressed())
|
||||
{
|
||||
ExecutionContext ec = ExecutionContext.Capture();
|
||||
if (ec is not null)
|
||||
{
|
||||
m_callerContext = ec.CreateCopy();
|
||||
ec.Dispose();
|
||||
ec = null;
|
||||
}
|
||||
}
|
||||
|
||||
m_callback = callback;
|
||||
m_callbackNoResult = null;
|
||||
m_state = state;
|
||||
m_workItemResult = new WorkItemResult(this);
|
||||
Initialize();
|
||||
}
|
||||
|
||||
public WorkItem(IWorkItemsGroup workItemsGroup, WorkItemInfo workItemInfo, WaitCallback callback, object state)
|
||||
{
|
||||
m_workItemsGroup = workItemsGroup;
|
||||
m_workItemInfo = workItemInfo;
|
||||
|
||||
if (m_workItemInfo.UseCallerCallContext && !ExecutionContext.IsFlowSuppressed())
|
||||
{
|
||||
ExecutionContext ec = ExecutionContext.Capture();
|
||||
if (ec is not null)
|
||||
{
|
||||
m_callerContext = ec.CreateCopy();
|
||||
ec.Dispose();
|
||||
ec = null;
|
||||
}
|
||||
}
|
||||
|
||||
m_callbackNoResult = callback;
|
||||
m_state = state;
|
||||
m_workItemResult = new WorkItemResult(this);
|
||||
Initialize();
|
||||
}
|
||||
|
||||
internal void Initialize()
|
||||
{
|
||||
// The _workItemState is changed directly instead of using the SetWorkItemState
|
||||
// method since we don't want to go throught IsValidStateTransition.
|
||||
m_workItemState = WorkItemState.InQueue;
|
||||
|
||||
m_workItemCompleted = null;
|
||||
m_workItemCompletedRefCount = 0;
|
||||
_waitingOnQueueStopwatch = new Stopwatch();
|
||||
_processingStopwatch = new Stopwatch();
|
||||
m_expirationTime = m_workItemInfo.Timeout > 0 ? DateTime.UtcNow.Ticks + m_workItemInfo.Timeout * TimeSpan.TicksPerMillisecond : long.MaxValue;
|
||||
}
|
||||
|
||||
internal bool WasQueuedBy(IWorkItemsGroup workItemsGroup)
|
||||
{
|
||||
return (workItemsGroup == m_workItemsGroup);
|
||||
}
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
#region Methods
|
||||
|
||||
internal CanceledWorkItemsGroup CanceledWorkItemsGroup
|
||||
{
|
||||
get { return m_canceledWorkItemsGroup; }
|
||||
set { m_canceledWorkItemsGroup = value; }
|
||||
}
|
||||
|
||||
internal CanceledWorkItemsGroup CanceledSmartThreadPool
|
||||
{
|
||||
get { return m_canceledSmartThreadPool; }
|
||||
set { m_canceledSmartThreadPool = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Change the state of the work item to in progress if it wasn't canceled.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// Return true on success or false in case the work item was canceled.
|
||||
/// If the work item needs to run a post execute then the method will return true.
|
||||
/// </returns>
|
||||
public bool StartingWorkItem()
|
||||
{
|
||||
_waitingOnQueueStopwatch.Stop();
|
||||
_processingStopwatch.Start();
|
||||
|
||||
lock (this)
|
||||
{
|
||||
if (IsCanceled)
|
||||
{
|
||||
if ((m_workItemInfo.PostExecuteWorkItemCallback is not null) &&
|
||||
((m_workItemInfo.CallToPostExecute & CallToPostExecute.WhenWorkItemCanceled) == CallToPostExecute.WhenWorkItemCanceled))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
Debug.Assert(WorkItemState.InQueue == GetWorkItemState());
|
||||
|
||||
// No need for a lock yet, only after the state has changed to InProgress
|
||||
m_executingThread = Thread.CurrentThread;
|
||||
|
||||
SetWorkItemState(WorkItemState.InProgress);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Execute the work item and the post execute
|
||||
/// </summary>
|
||||
public void Execute()
|
||||
{
|
||||
CallToPostExecute currentCallToPostExecute = 0;
|
||||
|
||||
// Execute the work item if we are in the correct state
|
||||
switch (GetWorkItemState())
|
||||
{
|
||||
case WorkItemState.InProgress:
|
||||
currentCallToPostExecute |= CallToPostExecute.WhenWorkItemNotCanceled;
|
||||
ExecuteWorkItem();
|
||||
break;
|
||||
case WorkItemState.Canceled:
|
||||
currentCallToPostExecute |= CallToPostExecute.WhenWorkItemCanceled;
|
||||
break;
|
||||
default:
|
||||
Debug.Assert(false);
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
// Run the post execute as needed
|
||||
if ((currentCallToPostExecute & m_workItemInfo.CallToPostExecute) != 0)
|
||||
{
|
||||
PostExecute();
|
||||
}
|
||||
|
||||
_processingStopwatch.Stop();
|
||||
}
|
||||
|
||||
internal void FireWorkItemCompleted()
|
||||
{
|
||||
try
|
||||
{
|
||||
m_workItemCompletedEvent?.Invoke(this);
|
||||
}
|
||||
catch // Suppress exceptions
|
||||
{ }
|
||||
}
|
||||
|
||||
internal void FireWorkItemStarted()
|
||||
{
|
||||
try
|
||||
{
|
||||
m_workItemStartedEvent?.Invoke(this);
|
||||
}
|
||||
catch // Suppress exceptions
|
||||
{ }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Execute the work item
|
||||
/// </summary>
|
||||
private void ExecuteWorkItem()
|
||||
{
|
||||
Exception exception = null;
|
||||
object result = null;
|
||||
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
if(m_callbackNoResult is null)
|
||||
{
|
||||
if(m_callerContext is null)
|
||||
result = m_callback(m_state);
|
||||
else
|
||||
{
|
||||
ContextCallback _ccb = new( o => { result =m_callback(o); });
|
||||
ExecutionContext.Run(m_callerContext, _ccb, m_state);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (m_callerContext is null)
|
||||
m_callbackNoResult(m_state);
|
||||
else
|
||||
{
|
||||
ContextCallback _ccb = new(o => { m_callbackNoResult(o); });
|
||||
ExecutionContext.Run(m_callerContext, _ccb, m_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// Save the exception so we can rethrow it later
|
||||
exception = e;
|
||||
}
|
||||
|
||||
// Remove the value of the execution thread, so it will be impossible to cancel the work item,
|
||||
// since it is already completed.
|
||||
// Cancelling a work item that already completed may cause the abortion of the next work item!!!
|
||||
Thread executionThread = Interlocked.CompareExchange(ref m_executingThread, null, m_executingThread);
|
||||
|
||||
if (executionThread is null)
|
||||
{
|
||||
// Oops! we are going to be aborted..., Wait here so we can catch the ThreadAbortException
|
||||
Thread.Sleep(60 * 1000);
|
||||
|
||||
// If after 1 minute this thread was not aborted then let it continue working.
|
||||
}
|
||||
}
|
||||
// We must treat the ThreadAbortException or else it will be stored in the exception variable
|
||||
catch (ThreadAbortException tae)
|
||||
{
|
||||
// Check if the work item was cancelled
|
||||
// If we got a ThreadAbortException and the STP is not shutting down, it means the
|
||||
// work items was cancelled.
|
||||
tae.GetHashCode();
|
||||
//if (!SmartThreadPool.CurrentThreadEntry.AssociatedSmartThreadPool.IsShuttingdown)
|
||||
//{
|
||||
// Thread.ResetAbort();
|
||||
//}
|
||||
}
|
||||
if (!SmartThreadPool.IsWorkItemCanceled)
|
||||
{
|
||||
SetResult(result, exception);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the post execute callback
|
||||
/// </summary>
|
||||
private void PostExecute()
|
||||
{
|
||||
if (m_workItemInfo.PostExecuteWorkItemCallback is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
m_workItemInfo.PostExecuteWorkItemCallback(m_workItemResult);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Assert(e is not null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Set the result of the work item to return
|
||||
/// </summary>
|
||||
/// <param name="result">The result of the work item</param>
|
||||
/// <param name="exception">The exception that was throw while the workitem executed, null
|
||||
/// if there was no exception.</param>
|
||||
internal void SetResult(object result, Exception exception)
|
||||
{
|
||||
m_result = result;
|
||||
m_exception = exception;
|
||||
SignalComplete(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the work item result
|
||||
/// </summary>
|
||||
/// <returns>The work item result</returns>
|
||||
internal IWorkItemResult GetWorkItemResult()
|
||||
{
|
||||
return m_workItemResult;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wait for all work items to complete
|
||||
/// </summary>
|
||||
/// <param name="waitableResults">Array of work item result objects</param>
|
||||
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
|
||||
/// <param name="exitContext">
|
||||
/// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
|
||||
/// </param>
|
||||
/// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
|
||||
/// <returns>
|
||||
/// true when every work item in waitableResults has completed; otherwise false.
|
||||
/// </returns>
|
||||
internal static bool WaitAll( IWaitableResult[] waitableResults, int millisecondsTimeout, bool exitContext,
|
||||
WaitHandle cancelWaitHandle)
|
||||
{
|
||||
if (0 == waitableResults.Length)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool success;
|
||||
WaitHandle[] waitHandles = new WaitHandle[waitableResults.Length];
|
||||
GetWaitHandles(waitableResults, waitHandles);
|
||||
|
||||
if ((cancelWaitHandle is null) && (waitHandles.Length <= 64))
|
||||
{
|
||||
success = STPEventWaitHandle.WaitAll(waitHandles, millisecondsTimeout, exitContext);
|
||||
}
|
||||
else
|
||||
{
|
||||
success = true;
|
||||
int millisecondsLeft = millisecondsTimeout;
|
||||
Stopwatch stopwatch = Stopwatch.StartNew();
|
||||
|
||||
WaitHandle[] whs = cancelWaitHandle is null ?
|
||||
new WaitHandle[] { null } :
|
||||
new WaitHandle[] { null, cancelWaitHandle };
|
||||
|
||||
bool waitInfinitely = (Timeout.Infinite == millisecondsTimeout);
|
||||
// Iterate over the wait handles and wait for each one to complete.
|
||||
// We cannot use WaitHandle.WaitAll directly, because the cancelWaitHandle
|
||||
// won't affect it.
|
||||
// Each iteration we update the time left for the timeout.
|
||||
for (int i = 0; i < waitableResults.Length; ++i)
|
||||
{
|
||||
// WaitAny don't work with negative numbers
|
||||
if (!waitInfinitely && (millisecondsLeft < 0))
|
||||
{
|
||||
success = false;
|
||||
break;
|
||||
}
|
||||
|
||||
whs[0] = waitHandles[i];
|
||||
int result = STPEventWaitHandle.WaitAny(whs, millisecondsLeft, exitContext);
|
||||
if ((result > 0) || (STPEventWaitHandle.WaitTimeout == result))
|
||||
{
|
||||
success = false;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!waitInfinitely)
|
||||
{
|
||||
// Update the time left to wait
|
||||
millisecondsLeft = millisecondsTimeout - (int)stopwatch.ElapsedMilliseconds;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Release the wait handles
|
||||
ReleaseWaitHandles(waitableResults);
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for any of the work items in the specified array to complete, cancel, or timeout
|
||||
/// </summary>
|
||||
/// <param name="waitableResults">Array of work item result objects</param>
|
||||
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
|
||||
/// <param name="exitContext">
|
||||
/// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
|
||||
/// </param>
|
||||
/// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
|
||||
/// <returns>
|
||||
/// The array index of the work item result that satisfied the wait, or WaitTimeout if no work item result satisfied the wait and a time interval equivalent to millisecondsTimeout has passed or the work item has been canceled.
|
||||
/// </returns>
|
||||
internal static int WaitAny( IWaitableResult[] waitableResults, int millisecondsTimeout,
|
||||
bool exitContext, WaitHandle cancelWaitHandle)
|
||||
{
|
||||
WaitHandle[] waitHandles;
|
||||
if (cancelWaitHandle is not null)
|
||||
{
|
||||
waitHandles = new WaitHandle[waitableResults.Length + 1];
|
||||
GetWaitHandles(waitableResults, waitHandles);
|
||||
waitHandles[waitableResults.Length] = cancelWaitHandle;
|
||||
}
|
||||
else
|
||||
{
|
||||
waitHandles = new WaitHandle[waitableResults.Length];
|
||||
GetWaitHandles(waitableResults, waitHandles);
|
||||
}
|
||||
|
||||
int result = STPEventWaitHandle.WaitAny(waitHandles, millisecondsTimeout, exitContext);
|
||||
|
||||
// Treat cancel as timeout
|
||||
if (cancelWaitHandle is not null)
|
||||
{
|
||||
if (result == waitableResults.Length)
|
||||
{
|
||||
result = STPEventWaitHandle.WaitTimeout;
|
||||
}
|
||||
}
|
||||
|
||||
ReleaseWaitHandles(waitableResults);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fill an array of wait handles with the work items wait handles.
|
||||
/// </summary>
|
||||
/// <param name="waitableResults">An array of work item results</param>
|
||||
/// <param name="waitHandles">An array of wait handles to fill</param>
|
||||
private static void GetWaitHandles(IWaitableResult[] waitableResults,
|
||||
WaitHandle[] waitHandles)
|
||||
{
|
||||
for (int i = 0; i < waitableResults.Length; ++i)
|
||||
{
|
||||
WorkItemResult wir = waitableResults[i].GetWorkItemResult() as WorkItemResult;
|
||||
Debug.Assert(wir is not null, "All waitableResults must be WorkItemResult objects");
|
||||
|
||||
waitHandles[i] = wir.GetWorkItem().GetWaitHandle();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Release the work items' wait handles
|
||||
/// </summary>
|
||||
/// <param name="waitableResults">An array of work item results</param>
|
||||
private static void ReleaseWaitHandles(IWaitableResult[] waitableResults)
|
||||
{
|
||||
for (int i = 0; i < waitableResults.Length; ++i)
|
||||
{
|
||||
WorkItemResult wir = (WorkItemResult)waitableResults[i].GetWorkItemResult();
|
||||
|
||||
wir.GetWorkItem().ReleaseWaitHandle();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Members
|
||||
|
||||
private WorkItemState GetWorkItemState()
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
if (WorkItemState.Completed == m_workItemState)
|
||||
{
|
||||
return m_workItemState;
|
||||
}
|
||||
if (WorkItemState.Canceled != m_workItemState && DateTime.UtcNow.Ticks > m_expirationTime)
|
||||
{
|
||||
m_workItemState = WorkItemState.Canceled;
|
||||
return m_workItemState;
|
||||
}
|
||||
if(WorkItemState.InProgress != m_workItemState)
|
||||
{
|
||||
if (CanceledSmartThreadPool.IsCanceled || CanceledWorkItemsGroup.IsCanceled)
|
||||
{
|
||||
return WorkItemState.Canceled;
|
||||
}
|
||||
}
|
||||
return m_workItemState;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Sets the work item's state
|
||||
/// </summary>
|
||||
/// <param name="workItemState">The state to set the work item to</param>
|
||||
private void SetWorkItemState(WorkItemState workItemState)
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
if (IsValidStatesTransition(m_workItemState, workItemState))
|
||||
{
|
||||
m_workItemState = workItemState;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Signals that work item has been completed or canceled
|
||||
/// </summary>
|
||||
/// <param name="canceled">Indicates that the work item has been canceled</param>
|
||||
private void SignalComplete(bool canceled)
|
||||
{
|
||||
SetWorkItemState(canceled ? WorkItemState.Canceled : WorkItemState.Completed);
|
||||
lock (this)
|
||||
{
|
||||
// If someone is waiting then signal.
|
||||
m_workItemCompleted?.Set();
|
||||
}
|
||||
}
|
||||
|
||||
internal void WorkItemIsQueued()
|
||||
{
|
||||
_waitingOnQueueStopwatch.Start();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Members exposed by WorkItemResult
|
||||
|
||||
/// <summary>
|
||||
/// Cancel the work item if it didn't start running yet.
|
||||
/// </summary>
|
||||
/// <returns>Returns true on success or false if the work item is in progress or already completed</returns>
|
||||
private bool Cancel(bool abortExecution)
|
||||
{
|
||||
bool success = false;
|
||||
bool signalComplete = false;
|
||||
|
||||
lock (this)
|
||||
{
|
||||
switch (GetWorkItemState())
|
||||
{
|
||||
case WorkItemState.Canceled:
|
||||
//Debug.WriteLine("Work item already canceled");
|
||||
if (abortExecution)
|
||||
{
|
||||
Thread executionThread = Interlocked.CompareExchange(ref m_executingThread, null, m_executingThread);
|
||||
if (executionThread is not null)
|
||||
{
|
||||
//executionThread.Abort(); // "Cancel"
|
||||
// No need to signalComplete, because we already cancelled this work item
|
||||
// so it already signaled its completion.
|
||||
//signalComplete = true;
|
||||
}
|
||||
}
|
||||
success = true;
|
||||
break;
|
||||
case WorkItemState.Completed:
|
||||
//Debug.WriteLine("Work item cannot be canceled");
|
||||
break;
|
||||
case WorkItemState.InProgress:
|
||||
if (abortExecution)
|
||||
{
|
||||
Thread executionThread = Interlocked.CompareExchange(ref m_executingThread, null, m_executingThread);
|
||||
if (executionThread is not null)
|
||||
{
|
||||
//executionThread.Abort(); // "Cancel"
|
||||
success = true;
|
||||
signalComplete = true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// **************************
|
||||
// Stock SmartThreadPool 2.2.3 sets these to true and relies on the thread to check the
|
||||
// WorkItem cancellation status. However, OpenSimulator uses a different mechanism to notify
|
||||
// scripts of co-operative termination and the abort code also relies on this method
|
||||
// returning false in order to implement a small wait.
|
||||
//
|
||||
// Therefore, as was the case previously with STP, we will not signal successful cancellation
|
||||
// here. It's possible that OpenSimulator code could be changed in the future to remove
|
||||
// the need for this change.
|
||||
// **************************
|
||||
success = false;
|
||||
signalComplete = false;
|
||||
}
|
||||
break;
|
||||
case WorkItemState.InQueue:
|
||||
// Signal to the wait for completion that the work
|
||||
// item has been completed (canceled). There is no
|
||||
// reason to wait for it to get out of the queue
|
||||
signalComplete = true;
|
||||
//Debug.WriteLine("Work item canceled");
|
||||
success = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (signalComplete)
|
||||
{
|
||||
SignalComplete(true);
|
||||
}
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the result of the work item.
|
||||
/// If the work item didn't run yet then the caller waits for the result, timeout, or cancel.
|
||||
/// In case of error the method throws and exception
|
||||
/// </summary>
|
||||
/// <returns>The result of the work item</returns>
|
||||
private object GetResult(int millisecondsTimeout, bool exitContext,
|
||||
WaitHandle cancelWaitHandle)
|
||||
{
|
||||
object result = GetResult(millisecondsTimeout, exitContext, cancelWaitHandle, out Exception e);
|
||||
if (e is not null)
|
||||
{
|
||||
throw new WorkItemResultException("The work item caused an excpetion, see the inner exception for details", e);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the result of the work item.
|
||||
/// If the work item didn't run yet then the caller waits for the result, timeout, or cancel.
|
||||
/// In case of error the e argument is filled with the exception
|
||||
/// </summary>
|
||||
/// <returns>The result of the work item</returns>
|
||||
private object GetResult( int millisecondsTimeout, bool exitContext,
|
||||
WaitHandle cancelWaitHandle, out Exception e)
|
||||
{
|
||||
e = null;
|
||||
|
||||
// Check for cancel
|
||||
if (WorkItemState.Canceled == GetWorkItemState())
|
||||
{
|
||||
throw new WorkItemCancelException("Work item canceled");
|
||||
}
|
||||
|
||||
// Check for completion
|
||||
if (IsCompleted)
|
||||
{
|
||||
e = m_exception;
|
||||
return m_result;
|
||||
}
|
||||
|
||||
// If no cancelWaitHandle is provided
|
||||
if (cancelWaitHandle is null)
|
||||
{
|
||||
WaitHandle wh = GetWaitHandle();
|
||||
|
||||
bool timeout = !STPEventWaitHandle.WaitOne(wh, millisecondsTimeout, exitContext);
|
||||
|
||||
ReleaseWaitHandle();
|
||||
|
||||
if (timeout)
|
||||
{
|
||||
throw new WorkItemTimeoutException("Work item timeout");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
WaitHandle wh = GetWaitHandle();
|
||||
int result = STPEventWaitHandle.WaitAny(new WaitHandle[] { wh, cancelWaitHandle });
|
||||
ReleaseWaitHandle();
|
||||
|
||||
switch (result)
|
||||
{
|
||||
case 0:
|
||||
// The work item signaled
|
||||
// Note that the signal could be also as a result of canceling the
|
||||
// work item (not the get result)
|
||||
break;
|
||||
case 1:
|
||||
case STPEventWaitHandle.WaitTimeout:
|
||||
throw new WorkItemTimeoutException("Work item timeout");
|
||||
default:
|
||||
Debug.Assert(false);
|
||||
break;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// Check for cancel
|
||||
if (WorkItemState.Canceled == GetWorkItemState())
|
||||
{
|
||||
throw new WorkItemCancelException("Work item canceled");
|
||||
}
|
||||
|
||||
Debug.Assert(IsCompleted);
|
||||
|
||||
e = m_exception;
|
||||
|
||||
// Return the result
|
||||
return m_result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A wait handle to wait for completion, cancel, or timeout
|
||||
/// </summary>
|
||||
private WaitHandle GetWaitHandle()
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
if (m_workItemCompleted is null)
|
||||
{
|
||||
m_workItemCompleted = new ManualResetEvent(IsCompleted);
|
||||
}
|
||||
++m_workItemCompletedRefCount;
|
||||
}
|
||||
return m_workItemCompleted;
|
||||
}
|
||||
|
||||
private void ReleaseWaitHandle()
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
if (m_workItemCompleted is not null)
|
||||
{
|
||||
--m_workItemCompletedRefCount;
|
||||
if (0 == m_workItemCompletedRefCount)
|
||||
{
|
||||
m_workItemCompleted.Close();
|
||||
m_workItemCompleted = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns true when the work item has completed or canceled
|
||||
/// </summary>
|
||||
private bool IsCompleted
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
WorkItemState workItemState = GetWorkItemState();
|
||||
return ((workItemState == WorkItemState.Completed) ||
|
||||
(workItemState == WorkItemState.Canceled));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns true when the work item has canceled
|
||||
/// </summary>
|
||||
public bool IsCanceled
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
return (GetWorkItemState() == WorkItemState.Canceled);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
internal event WorkItemStateCallback OnWorkItemStarted
|
||||
{
|
||||
add
|
||||
{
|
||||
m_workItemStartedEvent += value;
|
||||
}
|
||||
remove
|
||||
{
|
||||
m_workItemStartedEvent -= value;
|
||||
}
|
||||
}
|
||||
|
||||
internal event WorkItemStateCallback OnWorkItemCompleted
|
||||
{
|
||||
add
|
||||
{
|
||||
m_workItemCompletedEvent += value;
|
||||
}
|
||||
remove
|
||||
{
|
||||
m_workItemCompletedEvent -= value;
|
||||
}
|
||||
}
|
||||
|
||||
public void DisposeOfState()
|
||||
{
|
||||
if(m_callerContext is not null)
|
||||
{
|
||||
m_callerContext.Dispose();
|
||||
m_callerContext = null;
|
||||
}
|
||||
|
||||
if(m_workItemCompleted is not null)
|
||||
{
|
||||
m_workItemCompleted.Dispose();
|
||||
m_workItemCompleted = null;
|
||||
}
|
||||
|
||||
if (m_workItemInfo.DisposeOfStateObjects)
|
||||
{
|
||||
if (m_state is IDisposable disp)
|
||||
{
|
||||
disp.Dispose();
|
||||
m_state = null;
|
||||
}
|
||||
}
|
||||
m_callback = null;
|
||||
m_callbackNoResult = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
|
||||
namespace Amib.Threading.Internal
|
||||
{
|
||||
#region WorkItemFactory class
|
||||
|
||||
public class WorkItemFactory
|
||||
{
|
||||
|
||||
public static WorkItem CreateWorkItem(IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo, WorkItemInfo workItemInfo,
|
||||
WaitCallback callback, object state)
|
||||
{
|
||||
ValidateCallback(callback);
|
||||
ValidateCallback(workItemInfo.PostExecuteWorkItemCallback);
|
||||
return new WorkItem(workItemsGroup, new WorkItemInfo(workItemInfo), callback, state);
|
||||
|
||||
}
|
||||
|
||||
public static WorkItem CreateWorkItem(IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo,
|
||||
WaitCallback callback, object state)
|
||||
{
|
||||
ValidateCallback(callback);
|
||||
|
||||
WorkItemInfo workItemInfo = new()
|
||||
{
|
||||
UseCallerCallContext = wigStartInfo.UseCallerCallContext,
|
||||
PostExecuteWorkItemCallback = wigStartInfo.PostExecuteWorkItemCallback,
|
||||
CallToPostExecute = wigStartInfo.CallToPostExecute,
|
||||
DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects,
|
||||
};
|
||||
|
||||
return new WorkItem(workItemsGroup, workItemInfo, callback, state);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new work item
|
||||
/// </summary>
|
||||
/// <param name="workItemsGroup">The WorkItemsGroup of this workitem</param>
|
||||
/// <param name="wigStartInfo">Work item group start information</param>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <returns>Returns a work item</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static WorkItem CreateWorkItem( IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo, WorkItemCallback callback)
|
||||
{
|
||||
return CreateWorkItem(workItemsGroup, wigStartInfo, callback, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new work item
|
||||
/// </summary>
|
||||
/// <param name="workItemsGroup">The WorkItemsGroup of this workitem</param>
|
||||
/// <param name="wigStartInfo">Work item group start information</param>
|
||||
/// <param name="workItemInfo">Work item info</param>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <returns>Returns a work item</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static WorkItem CreateWorkItem( IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo,
|
||||
WorkItemInfo workItemInfo, WorkItemCallback callback)
|
||||
{
|
||||
return CreateWorkItem(workItemsGroup, wigStartInfo, workItemInfo, callback, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new work item
|
||||
/// </summary>
|
||||
/// <param name="workItemsGroup">The WorkItemsGroup of this workitem</param>
|
||||
/// <param name="wigStartInfo">Work item group start information</param>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <param name="state">
|
||||
/// The context object of the work item. Used for passing arguments to the work item.
|
||||
/// </param>
|
||||
/// <returns>Returns a work item</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static WorkItem CreateWorkItem( IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo,
|
||||
WorkItemCallback callback, object state)
|
||||
{
|
||||
ValidateCallback(callback);
|
||||
|
||||
WorkItemInfo workItemInfo = new()
|
||||
{
|
||||
UseCallerCallContext = wigStartInfo.UseCallerCallContext,
|
||||
PostExecuteWorkItemCallback = wigStartInfo.PostExecuteWorkItemCallback,
|
||||
CallToPostExecute = wigStartInfo.CallToPostExecute,
|
||||
DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects,
|
||||
};
|
||||
|
||||
return new WorkItem( workItemsGroup, workItemInfo, callback, state);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new work item
|
||||
/// </summary>
|
||||
/// <param name="workItemsGroup">The work items group</param>
|
||||
/// <param name="wigStartInfo">Work item group start information</param>
|
||||
/// <param name="workItemInfo">Work item information</param>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <param name="state">
|
||||
/// The context object of the work item. Used for passing arguments to the work item.
|
||||
/// </param>
|
||||
/// <returns>Returns a work item</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static WorkItem CreateWorkItem( IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo, WorkItemInfo workItemInfo,
|
||||
WorkItemCallback callback, object state)
|
||||
{
|
||||
ValidateCallback(callback);
|
||||
ValidateCallback(workItemInfo.PostExecuteWorkItemCallback);
|
||||
|
||||
WorkItem workItem = new(
|
||||
workItemsGroup,
|
||||
new WorkItemInfo(workItemInfo),
|
||||
callback,
|
||||
state);
|
||||
|
||||
return workItem;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new work item
|
||||
/// </summary>
|
||||
/// <param name="workItemsGroup">The work items group</param>
|
||||
/// <param name="wigStartInfo">Work item group start information</param>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <param name="state">
|
||||
/// The context object of the work item. Used for passing arguments to the work item.
|
||||
/// </param>
|
||||
/// <param name="postExecuteWorkItemCallback">
|
||||
/// A delegate to call after the callback completion
|
||||
/// </param>
|
||||
/// <returns>Returns a work item</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static WorkItem CreateWorkItem(IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo,
|
||||
WorkItemCallback callback, object state,PostExecuteWorkItemCallback postExecuteWorkItemCallback)
|
||||
{
|
||||
ValidateCallback(callback);
|
||||
ValidateCallback(postExecuteWorkItemCallback);
|
||||
|
||||
WorkItemInfo workItemInfo = new()
|
||||
{
|
||||
UseCallerCallContext = wigStartInfo.UseCallerCallContext,
|
||||
PostExecuteWorkItemCallback = postExecuteWorkItemCallback,
|
||||
CallToPostExecute = wigStartInfo.CallToPostExecute,
|
||||
DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects
|
||||
};
|
||||
|
||||
return new WorkItem( workItemsGroup, workItemInfo, callback, state);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new work item
|
||||
/// </summary>
|
||||
/// <param name="workItemsGroup">The work items group</param>
|
||||
/// <param name="wigStartInfo">Work item group start information</param>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <param name="state">
|
||||
/// The context object of the work item. Used for passing arguments to the work item.
|
||||
/// </param>
|
||||
/// <param name="postExecuteWorkItemCallback">
|
||||
/// A delegate to call after the callback completion
|
||||
/// </param>
|
||||
/// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
|
||||
/// <returns>Returns a work item</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static WorkItem CreateWorkItem(IWorkItemsGroup workItemsGroup,WIGStartInfo wigStartInfo,
|
||||
WorkItemCallback callback, object state,
|
||||
PostExecuteWorkItemCallback postExecuteWorkItemCallback, CallToPostExecute callToPostExecute)
|
||||
{
|
||||
ValidateCallback(callback);
|
||||
ValidateCallback(postExecuteWorkItemCallback);
|
||||
|
||||
WorkItemInfo workItemInfo = new()
|
||||
{
|
||||
UseCallerCallContext = wigStartInfo.UseCallerCallContext,
|
||||
PostExecuteWorkItemCallback = postExecuteWorkItemCallback,
|
||||
CallToPostExecute = callToPostExecute,
|
||||
DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects
|
||||
};
|
||||
|
||||
return new WorkItem(workItemsGroup, workItemInfo, callback, state);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static void ValidateCallback(Delegate callback)
|
||||
{
|
||||
if (callback is not null && callback.GetInvocationList().Length > 1)
|
||||
{
|
||||
throw new NotSupportedException("SmartThreadPool doesn't support delegates chains");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
namespace Amib.Threading
|
||||
{
|
||||
#region WorkItemInfo class
|
||||
|
||||
/// <summary>
|
||||
/// Summary description for WorkItemInfo.
|
||||
/// </summary>
|
||||
public class WorkItemInfo
|
||||
{
|
||||
public WorkItemInfo()
|
||||
{
|
||||
UseCallerCallContext = SmartThreadPool.DefaultUseCallerCallContext;
|
||||
DisposeOfStateObjects = SmartThreadPool.DefaultDisposeOfStateObjects;
|
||||
CallToPostExecute = SmartThreadPool.DefaultCallToPostExecute;
|
||||
PostExecuteWorkItemCallback = SmartThreadPool.DefaultPostExecuteWorkItemCallback;
|
||||
}
|
||||
|
||||
public WorkItemInfo(WorkItemInfo workItemInfo)
|
||||
{
|
||||
UseCallerCallContext = workItemInfo.UseCallerCallContext;
|
||||
DisposeOfStateObjects = workItemInfo.DisposeOfStateObjects;
|
||||
CallToPostExecute = workItemInfo.CallToPostExecute;
|
||||
PostExecuteWorkItemCallback = workItemInfo.PostExecuteWorkItemCallback;
|
||||
Timeout = workItemInfo.Timeout;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set if to use the caller's security context
|
||||
/// </summary>
|
||||
public bool UseCallerCallContext { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set if to dispose of the state object of a work item
|
||||
/// </summary>
|
||||
public bool DisposeOfStateObjects { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set the run the post execute options
|
||||
/// </summary>
|
||||
public CallToPostExecute CallToPostExecute { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set the post execute callback
|
||||
/// </summary>
|
||||
public PostExecuteWorkItemCallback PostExecuteWorkItemCallback { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set the work item's timout in milliseconds.
|
||||
/// This is a passive timout. When the timout expires the work item won't be actively aborted!
|
||||
/// </summary>
|
||||
public long Timeout { get; set; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace Amib.Threading.Internal
|
||||
{
|
||||
#region WorkItemResultTWrapper class
|
||||
|
||||
internal class WorkItemResultTWrapper<TResult> : IWorkItemResult<TResult>, IInternalWaitableResult
|
||||
{
|
||||
private readonly IWorkItemResult _workItemResult;
|
||||
|
||||
public WorkItemResultTWrapper(IWorkItemResult workItemResult)
|
||||
{
|
||||
_workItemResult = workItemResult;
|
||||
}
|
||||
|
||||
#region IWorkItemResult<TResult> Members
|
||||
|
||||
public TResult GetResult()
|
||||
{
|
||||
return (TResult)_workItemResult.GetResult();
|
||||
}
|
||||
|
||||
public TResult GetResult(int millisecondsTimeout, bool exitContext)
|
||||
{
|
||||
return (TResult)_workItemResult.GetResult(millisecondsTimeout, exitContext);
|
||||
}
|
||||
|
||||
public TResult GetResult(TimeSpan timeout, bool exitContext)
|
||||
{
|
||||
return (TResult)_workItemResult.GetResult(timeout, exitContext);
|
||||
}
|
||||
|
||||
public TResult GetResult(int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle)
|
||||
{
|
||||
return (TResult)_workItemResult.GetResult(millisecondsTimeout, exitContext, cancelWaitHandle);
|
||||
}
|
||||
|
||||
public TResult GetResult(TimeSpan timeout, bool exitContext, WaitHandle cancelWaitHandle)
|
||||
{
|
||||
return (TResult)_workItemResult.GetResult(timeout, exitContext, cancelWaitHandle);
|
||||
}
|
||||
|
||||
public TResult GetResult(out Exception e)
|
||||
{
|
||||
return (TResult)_workItemResult.GetResult(out e);
|
||||
}
|
||||
|
||||
public TResult GetResult(int millisecondsTimeout, bool exitContext, out Exception e)
|
||||
{
|
||||
return (TResult)_workItemResult.GetResult(millisecondsTimeout, exitContext, out e);
|
||||
}
|
||||
|
||||
public TResult GetResult(TimeSpan timeout, bool exitContext, out Exception e)
|
||||
{
|
||||
return (TResult)_workItemResult.GetResult(timeout, exitContext, out e);
|
||||
}
|
||||
|
||||
public TResult GetResult(int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e)
|
||||
{
|
||||
return (TResult)_workItemResult.GetResult(millisecondsTimeout, exitContext, cancelWaitHandle, out e);
|
||||
}
|
||||
|
||||
public TResult GetResult(TimeSpan timeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e)
|
||||
{
|
||||
return (TResult)_workItemResult.GetResult(timeout, exitContext, cancelWaitHandle, out e);
|
||||
}
|
||||
|
||||
public bool IsCompleted
|
||||
{
|
||||
get { return _workItemResult.IsCompleted; }
|
||||
}
|
||||
|
||||
public bool IsCanceled
|
||||
{
|
||||
get { return _workItemResult.IsCanceled; }
|
||||
}
|
||||
|
||||
public object State
|
||||
{
|
||||
get { return _workItemResult.State; }
|
||||
}
|
||||
|
||||
public bool Cancel()
|
||||
{
|
||||
return _workItemResult.Cancel();
|
||||
}
|
||||
|
||||
public bool Cancel(bool abortExecution)
|
||||
{
|
||||
return _workItemResult.Cancel(abortExecution);
|
||||
}
|
||||
|
||||
public TResult Result
|
||||
{
|
||||
get { return (TResult)_workItemResult.Result; }
|
||||
}
|
||||
|
||||
public object Exception
|
||||
{
|
||||
get { return (TResult)_workItemResult.Exception; }
|
||||
}
|
||||
|
||||
#region IInternalWorkItemResult Members
|
||||
|
||||
public IWorkItemResult GetWorkItemResult()
|
||||
{
|
||||
return _workItemResult.GetWorkItemResult();
|
||||
}
|
||||
|
||||
public IWorkItemResult<TRes> GetWorkItemResultT<TRes>()
|
||||
{
|
||||
return (IWorkItemResult<TRes>)this;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
+354
@@ -0,0 +1,354 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Amib.Threading.Internal
|
||||
{
|
||||
|
||||
#region WorkItemsGroup class
|
||||
|
||||
/// <summary>
|
||||
/// Summary description for WorkItemsGroup.
|
||||
/// </summary>
|
||||
public class WorkItemsGroup : WorkItemsGroupBase
|
||||
{
|
||||
#region Private members
|
||||
|
||||
private readonly object _lock = new();
|
||||
|
||||
/// <summary>
|
||||
/// A reference to the SmartThreadPool instance that created this
|
||||
/// WorkItemsGroup.
|
||||
/// </summary>
|
||||
private readonly SmartThreadPool _stp;
|
||||
|
||||
/// <summary>
|
||||
/// The OnIdle event
|
||||
/// </summary>
|
||||
private event WorkItemsGroupIdleHandler _onIdle;
|
||||
|
||||
/// <summary>
|
||||
/// A flag to indicate if the Work Items Group is now suspended.
|
||||
/// </summary>
|
||||
private bool _isSuspended;
|
||||
|
||||
/// <summary>
|
||||
/// Defines how many work items of this WorkItemsGroup can run at once.
|
||||
/// </summary>
|
||||
private int _concurrency;
|
||||
|
||||
/// <summary>
|
||||
/// Priority queue to hold work items before they are passed
|
||||
/// to the SmartThreadPool.
|
||||
/// </summary>
|
||||
private readonly Queue<WorkItem> _workItemsQueue;
|
||||
|
||||
/// <summary>
|
||||
/// Indicate how many work items are waiting in the SmartThreadPool
|
||||
/// queue.
|
||||
/// This value is used to apply the concurrency.
|
||||
/// </summary>
|
||||
private int _workItemsInStpQueue;
|
||||
|
||||
/// <summary>
|
||||
/// Indicate how many work items are currently running in the SmartThreadPool.
|
||||
/// This value is used with the Cancel, to calculate if we can send new
|
||||
/// work items to the STP.
|
||||
/// </summary>
|
||||
private int _workItemsExecutingInStp = 0;
|
||||
|
||||
/// <summary>
|
||||
/// WorkItemsGroup start information
|
||||
/// </summary>
|
||||
private readonly WIGStartInfo _workItemsGroupStartInfo;
|
||||
|
||||
/// <summary>
|
||||
/// Signaled when all of the WorkItemsGroup's work item completed.
|
||||
/// </summary>
|
||||
private readonly ManualResetEvent _isIdleWaitHandle = new(true);
|
||||
|
||||
/// <summary>
|
||||
/// A common object for all the work items that this work items group
|
||||
/// generate so we can mark them to cancel in O(1)
|
||||
/// </summary>
|
||||
private CanceledWorkItemsGroup _canceledWorkItemsGroup = new();
|
||||
|
||||
#endregion
|
||||
|
||||
#region Construction
|
||||
|
||||
public WorkItemsGroup(SmartThreadPool stp, int concurrency, WIGStartInfo wigStartInfo)
|
||||
{
|
||||
if (concurrency <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(
|
||||
"concurrency",
|
||||
concurrency,
|
||||
"concurrency must be greater than zero");
|
||||
}
|
||||
_stp = stp;
|
||||
_concurrency = concurrency;
|
||||
_workItemsGroupStartInfo = new WIGStartInfo(wigStartInfo).AsReadOnly();
|
||||
_workItemsQueue = new Queue<WorkItem>();
|
||||
Name = "WorkItemsGroup";
|
||||
|
||||
// The _workItemsInStpQueue gets the number of currently executing work items,
|
||||
// because once a work item is executing, it cannot be cancelled.
|
||||
_workItemsInStpQueue = _workItemsExecutingInStp;
|
||||
|
||||
_isSuspended = _workItemsGroupStartInfo.StartSuspended;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region WorkItemsGroupBase Overrides
|
||||
|
||||
public override int Concurrency
|
||||
{
|
||||
get { return _concurrency; }
|
||||
set
|
||||
{
|
||||
Debug.Assert(value > 0);
|
||||
|
||||
int diff = value - _concurrency;
|
||||
_concurrency = value;
|
||||
if (diff > 0)
|
||||
{
|
||||
EnqueueToSTPNextNWorkItem(diff);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override int WaitingCallbacks
|
||||
{
|
||||
get { return _workItemsQueue.Count; }
|
||||
}
|
||||
|
||||
public override object[] GetStates()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
object[] states = new object[_workItemsQueue.Count];
|
||||
int i = 0;
|
||||
foreach (WorkItem workItem in _workItemsQueue)
|
||||
{
|
||||
states[i] = workItem.GetWorkItemResult().State;
|
||||
++i;
|
||||
}
|
||||
return states;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// WorkItemsGroup start information
|
||||
/// </summary>
|
||||
public override WIGStartInfo WIGStartInfo
|
||||
{
|
||||
get { return _workItemsGroupStartInfo; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Start the Work Items Group if it was started suspended
|
||||
/// </summary>
|
||||
public override void Start()
|
||||
{
|
||||
// If the Work Items Group already started then quit
|
||||
if (!_isSuspended)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_isSuspended = false;
|
||||
|
||||
EnqueueToSTPNextNWorkItem(Math.Min(_workItemsQueue.Count, _concurrency));
|
||||
}
|
||||
|
||||
public override void Cancel(bool abortExecution)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_canceledWorkItemsGroup.IsCanceled = true;
|
||||
_workItemsQueue.Clear();
|
||||
_workItemsInStpQueue = 0;
|
||||
_canceledWorkItemsGroup = new CanceledWorkItemsGroup();
|
||||
}
|
||||
|
||||
if (abortExecution)
|
||||
{
|
||||
_stp.CancelAbortWorkItemsGroup(this);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wait for the thread pool to be idle
|
||||
/// </summary>
|
||||
public override bool WaitForIdle(int millisecondsTimeout)
|
||||
{
|
||||
SmartThreadPool.ValidateWorkItemsGroupWaitForIdle(this);
|
||||
return STPEventWaitHandle.WaitOne(_isIdleWaitHandle, millisecondsTimeout, false);
|
||||
}
|
||||
|
||||
public override event WorkItemsGroupIdleHandler OnIdle
|
||||
{
|
||||
add { _onIdle += value; }
|
||||
remove { _onIdle -= value; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private methods
|
||||
|
||||
private void RegisterToWorkItemCompletion(IWorkItemResult wir)
|
||||
{
|
||||
IInternalWorkItemResult iwir = (IInternalWorkItemResult)wir;
|
||||
iwir.OnWorkItemStarted += OnWorkItemStartedCallback;
|
||||
iwir.OnWorkItemCompleted += OnWorkItemCompletedCallback;
|
||||
}
|
||||
|
||||
public void OnSTPIsStarting()
|
||||
{
|
||||
if (_isSuspended)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
EnqueueToSTPNextNWorkItem(_concurrency);
|
||||
}
|
||||
|
||||
public void EnqueueToSTPNextNWorkItem(int count)
|
||||
{
|
||||
for (int i = 0; i < count; ++i)
|
||||
{
|
||||
EnqueueToSTPNextWorkItem(null, false);
|
||||
}
|
||||
}
|
||||
|
||||
private object FireOnIdle(object state)
|
||||
{
|
||||
FireOnIdleImpl(_onIdle);
|
||||
return null;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private void FireOnIdleImpl(WorkItemsGroupIdleHandler onIdle)
|
||||
{
|
||||
if(onIdle is null)
|
||||
return;
|
||||
|
||||
Delegate[] delegates = onIdle.GetInvocationList();
|
||||
foreach(WorkItemsGroupIdleHandler eh in delegates)
|
||||
{
|
||||
try
|
||||
{
|
||||
eh(this);
|
||||
}
|
||||
catch { } // Suppress exceptions
|
||||
}
|
||||
}
|
||||
|
||||
private void OnWorkItemStartedCallback(WorkItem workItem)
|
||||
{
|
||||
lock(_lock)
|
||||
{
|
||||
++_workItemsExecutingInStp;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnWorkItemCompletedCallback(WorkItem workItem)
|
||||
{
|
||||
EnqueueToSTPNextWorkItem(null, true);
|
||||
}
|
||||
|
||||
internal override void Enqueue(WorkItem workItem)
|
||||
{
|
||||
EnqueueToSTPNextWorkItem(workItem);
|
||||
}
|
||||
|
||||
private void EnqueueToSTPNextWorkItem(WorkItem workItem)
|
||||
{
|
||||
EnqueueToSTPNextWorkItem(workItem, false);
|
||||
}
|
||||
|
||||
private void EnqueueToSTPNextWorkItem(WorkItem workItem, bool decrementWorkItemsInStpQueue)
|
||||
{
|
||||
lock(_lock)
|
||||
{
|
||||
// Got here from OnWorkItemCompletedCallback()
|
||||
if (decrementWorkItemsInStpQueue)
|
||||
{
|
||||
--_workItemsInStpQueue;
|
||||
|
||||
if(_workItemsInStpQueue < 0)
|
||||
{
|
||||
_workItemsInStpQueue = 0;
|
||||
}
|
||||
|
||||
--_workItemsExecutingInStp;
|
||||
|
||||
if(_workItemsExecutingInStp < 0)
|
||||
{
|
||||
_workItemsExecutingInStp = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// If the work item is not null then enqueue it
|
||||
if (workItem is not null)
|
||||
{
|
||||
workItem.CanceledWorkItemsGroup = _canceledWorkItemsGroup;
|
||||
|
||||
RegisterToWorkItemCompletion(workItem.GetWorkItemResult());
|
||||
_workItemsQueue.Enqueue(workItem);
|
||||
//_stp.IncrementWorkItemsCount();
|
||||
|
||||
if ((1 == _workItemsQueue.Count) &&
|
||||
(0 == _workItemsInStpQueue))
|
||||
{
|
||||
_stp.RegisterWorkItemsGroup(this);
|
||||
IsIdle = false;
|
||||
_isIdleWaitHandle.Reset();
|
||||
}
|
||||
}
|
||||
|
||||
// If the work items queue of the group is empty than quit
|
||||
if (0 == _workItemsQueue.Count)
|
||||
{
|
||||
if (0 == _workItemsInStpQueue)
|
||||
{
|
||||
_stp.UnregisterWorkItemsGroup(this);
|
||||
IsIdle = true;
|
||||
_isIdleWaitHandle.Set();
|
||||
if (decrementWorkItemsInStpQueue && _onIdle is not null && _onIdle.GetInvocationList().Length > 0)
|
||||
{
|
||||
_stp.QueueWorkItem(new WorkItemCallback(FireOnIdle));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_isSuspended)
|
||||
{
|
||||
if (_workItemsInStpQueue < _concurrency)
|
||||
{
|
||||
WorkItem nextWorkItem = _workItemsQueue.Dequeue();
|
||||
try
|
||||
{
|
||||
_stp.Enqueue(nextWorkItem);
|
||||
}
|
||||
catch (ObjectDisposedException e)
|
||||
{
|
||||
e.GetHashCode();
|
||||
// The STP has been shutdown
|
||||
}
|
||||
|
||||
++_workItemsInStpQueue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
+388
@@ -0,0 +1,388 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace Amib.Threading.Internal
|
||||
{
|
||||
public abstract class WorkItemsGroupBase : IWorkItemsGroup
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
/// <summary>
|
||||
/// Contains the name of this instance of SmartThreadPool.
|
||||
/// Can be changed by the user.
|
||||
/// </summary>
|
||||
private string _name = "WorkItemsGroupBase";
|
||||
|
||||
public WorkItemsGroupBase()
|
||||
{
|
||||
IsIdle = true;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IWorkItemsGroup Members
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Get/Set the name of the SmartThreadPool/WorkItemsGroup instance
|
||||
/// </summary>
|
||||
public string Name
|
||||
{
|
||||
get { return _name; }
|
||||
set { _name = value; }
|
||||
}
|
||||
|
||||
public int localID { get; set;}
|
||||
#endregion
|
||||
|
||||
#region Abstract Methods
|
||||
|
||||
public abstract int Concurrency { get; set; }
|
||||
public abstract int WaitingCallbacks { get; }
|
||||
public abstract object[] GetStates();
|
||||
public abstract WIGStartInfo WIGStartInfo { get; }
|
||||
public abstract void Start();
|
||||
public abstract void Cancel(bool abortExecution);
|
||||
public abstract bool WaitForIdle(int millisecondsTimeout);
|
||||
public abstract event WorkItemsGroupIdleHandler OnIdle;
|
||||
|
||||
internal abstract void Enqueue(WorkItem workItem);
|
||||
internal virtual void PreQueueWorkItem() { }
|
||||
|
||||
#endregion
|
||||
|
||||
#region Common Base Methods
|
||||
|
||||
/// <summary>
|
||||
/// Cancel all the work items.
|
||||
/// Same as Cancel(false)
|
||||
/// </summary>
|
||||
public virtual void Cancel()
|
||||
{
|
||||
Cancel(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wait for the SmartThreadPool/WorkItemsGroup to be idle
|
||||
/// </summary>
|
||||
public void WaitForIdle()
|
||||
{
|
||||
WaitForIdle(Timeout.Infinite);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wait for the SmartThreadPool/WorkItemsGroup to be idle
|
||||
/// </summary>
|
||||
public bool WaitForIdle(TimeSpan timeout)
|
||||
{
|
||||
return WaitForIdle((int)timeout.TotalMilliseconds);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// IsIdle is true when there are no work items running or queued.
|
||||
/// </summary>
|
||||
public bool IsIdle { get; protected set; }
|
||||
|
||||
#endregion
|
||||
|
||||
#region QueueWorkItem
|
||||
|
||||
public IWorkItemResult QueueWorkItem(WaitCallback callback)
|
||||
{
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, null);
|
||||
Enqueue(workItem);
|
||||
return workItem.GetWorkItemResult();
|
||||
}
|
||||
|
||||
public IWorkItemResult QueueWorkItem(WaitCallback callback, object state)
|
||||
{
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state);
|
||||
Enqueue(workItem);
|
||||
return workItem.GetWorkItemResult();
|
||||
}
|
||||
|
||||
public IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WaitCallback callback)
|
||||
{
|
||||
PreQueueWorkItem();
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, workItemInfo, callback, null);
|
||||
Enqueue(workItem);
|
||||
return workItem.GetWorkItemResult();
|
||||
}
|
||||
|
||||
public IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WaitCallback callback, object state)
|
||||
{
|
||||
PreQueueWorkItem();
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, workItemInfo, callback, state);
|
||||
Enqueue(workItem);
|
||||
return workItem.GetWorkItemResult();
|
||||
}
|
||||
/// <summary>
|
||||
/// Queue a work item
|
||||
/// </summary>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <returns>Returns a work item result</returns>
|
||||
public IWorkItemResult QueueWorkItem(WorkItemCallback callback)
|
||||
{
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback);
|
||||
Enqueue(workItem);
|
||||
return workItem.GetWorkItemResult();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item
|
||||
/// </summary>
|
||||
/// <param name="workItemInfo">Work item info</param>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <returns>Returns a work item result</returns>
|
||||
public IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback)
|
||||
{
|
||||
PreQueueWorkItem();
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, workItemInfo, callback);
|
||||
Enqueue(workItem);
|
||||
return workItem.GetWorkItemResult();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item
|
||||
/// </summary>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <param name="state">
|
||||
/// The context object of the work item. Used for passing arguments to the work item.
|
||||
/// </param>
|
||||
/// <returns>Returns a work item result</returns>
|
||||
public IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state)
|
||||
{
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state);
|
||||
Enqueue(workItem);
|
||||
return workItem.GetWorkItemResult();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item
|
||||
/// </summary>
|
||||
/// <param name="workItemInfo">Work item information</param>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <param name="state">
|
||||
/// The context object of the work item. Used for passing arguments to the work item.
|
||||
/// </param>
|
||||
/// <returns>Returns a work item result</returns>
|
||||
public IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback, object state)
|
||||
{
|
||||
PreQueueWorkItem();
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, workItemInfo, callback, state);
|
||||
Enqueue(workItem);
|
||||
return workItem.GetWorkItemResult();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item
|
||||
/// </summary>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <param name="state">
|
||||
/// The context object of the work item. Used for passing arguments to the work item.
|
||||
/// </param>
|
||||
/// <param name="postExecuteWorkItemCallback">
|
||||
/// A delegate to call after the callback completion
|
||||
/// </param>
|
||||
/// <returns>Returns a work item result</returns>
|
||||
public IWorkItemResult QueueWorkItem( WorkItemCallback callback, object state,
|
||||
PostExecuteWorkItemCallback postExecuteWorkItemCallback)
|
||||
{
|
||||
PreQueueWorkItem();
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback);
|
||||
Enqueue(workItem);
|
||||
return workItem.GetWorkItemResult();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Queue a work item
|
||||
/// </summary>
|
||||
/// <param name="callback">A callback to execute</param>
|
||||
/// <param name="state">
|
||||
/// The context object of the work item. Used for passing arguments to the work item.
|
||||
/// </param>
|
||||
/// <param name="postExecuteWorkItemCallback">
|
||||
/// A delegate to call after the callback completion
|
||||
/// </param>
|
||||
/// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
|
||||
/// <returns>Returns a work item result</returns>
|
||||
public IWorkItemResult QueueWorkItem( WorkItemCallback callback, object state,
|
||||
PostExecuteWorkItemCallback postExecuteWorkItemCallback, CallToPostExecute callToPostExecute)
|
||||
{
|
||||
PreQueueWorkItem();
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback, callToPostExecute);
|
||||
Enqueue(workItem);
|
||||
return workItem.GetWorkItemResult();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region QueueWorkItem(Action<...>)
|
||||
|
||||
public IWorkItemResult QueueWorkItem (Action action)
|
||||
{
|
||||
PreQueueWorkItem ();
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem (
|
||||
this,
|
||||
WIGStartInfo,
|
||||
delegate
|
||||
{
|
||||
action.Invoke ();
|
||||
return null;
|
||||
});
|
||||
Enqueue (workItem);
|
||||
return workItem.GetWorkItemResult ();
|
||||
}
|
||||
|
||||
public IWorkItemResult QueueWorkItem<T> (Action<T> action, T arg)
|
||||
{
|
||||
PreQueueWorkItem ();
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem (
|
||||
this,
|
||||
WIGStartInfo,
|
||||
state =>
|
||||
{
|
||||
action.Invoke (arg);
|
||||
return null;
|
||||
},
|
||||
WIGStartInfo.FillStateWithArgs ? new object[] { arg } : null);
|
||||
Enqueue (workItem);
|
||||
return workItem.GetWorkItemResult ();
|
||||
}
|
||||
|
||||
public IWorkItemResult QueueWorkItem<T1, T2> (Action<T1, T2> action, T1 arg1, T2 arg2)
|
||||
{
|
||||
PreQueueWorkItem ();
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem (
|
||||
this,
|
||||
WIGStartInfo,
|
||||
state =>
|
||||
{
|
||||
action.Invoke (arg1, arg2);
|
||||
return null;
|
||||
},
|
||||
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2 } : null);
|
||||
Enqueue (workItem);
|
||||
return workItem.GetWorkItemResult ();
|
||||
}
|
||||
|
||||
public IWorkItemResult QueueWorkItem<T1, T2, T3> (Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3)
|
||||
{
|
||||
PreQueueWorkItem ();
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem (
|
||||
this,
|
||||
WIGStartInfo,
|
||||
state =>
|
||||
{
|
||||
action.Invoke (arg1, arg2, arg3);
|
||||
return null;
|
||||
},
|
||||
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3 } : null);
|
||||
Enqueue (workItem);
|
||||
return workItem.GetWorkItemResult ();
|
||||
}
|
||||
|
||||
public IWorkItemResult QueueWorkItem<T1, T2, T3, T4> (
|
||||
Action<T1, T2, T3, T4> action, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
|
||||
{
|
||||
PreQueueWorkItem ();
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem (
|
||||
this,
|
||||
WIGStartInfo,
|
||||
state =>
|
||||
{
|
||||
action.Invoke (arg1, arg2, arg3, arg4);
|
||||
return null;
|
||||
},
|
||||
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3, arg4 } : null);
|
||||
Enqueue (workItem);
|
||||
return workItem.GetWorkItemResult ();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region QueueWorkItem(Func<...>)
|
||||
|
||||
public IWorkItemResult<TResult> QueueWorkItem<TResult>(Func<TResult> func)
|
||||
{
|
||||
PreQueueWorkItem();
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem(
|
||||
this,
|
||||
WIGStartInfo,
|
||||
state =>
|
||||
{
|
||||
return func.Invoke();
|
||||
});
|
||||
Enqueue(workItem);
|
||||
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
|
||||
}
|
||||
|
||||
public IWorkItemResult<TResult> QueueWorkItem<T, TResult>(Func<T, TResult> func, T arg)
|
||||
{
|
||||
PreQueueWorkItem();
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem(
|
||||
this,
|
||||
WIGStartInfo,
|
||||
state =>
|
||||
{
|
||||
return func.Invoke(arg);
|
||||
},
|
||||
WIGStartInfo.FillStateWithArgs ? new object[] { arg } : null);
|
||||
Enqueue(workItem);
|
||||
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
|
||||
}
|
||||
|
||||
public IWorkItemResult<TResult> QueueWorkItem<T1, T2, TResult>(Func<T1, T2, TResult> func, T1 arg1, T2 arg2)
|
||||
{
|
||||
PreQueueWorkItem();
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem(
|
||||
this,
|
||||
WIGStartInfo,
|
||||
state =>
|
||||
{
|
||||
return func.Invoke(arg1, arg2);
|
||||
},
|
||||
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2 } : null);
|
||||
Enqueue(workItem);
|
||||
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
|
||||
}
|
||||
|
||||
public IWorkItemResult<TResult> QueueWorkItem<T1, T2, T3, TResult>(
|
||||
Func<T1, T2, T3, TResult> func, T1 arg1, T2 arg2, T3 arg3)
|
||||
{
|
||||
PreQueueWorkItem();
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem(
|
||||
this,
|
||||
WIGStartInfo,
|
||||
state =>
|
||||
{
|
||||
return func.Invoke(arg1, arg2, arg3);
|
||||
},
|
||||
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3 } : null);
|
||||
Enqueue(workItem);
|
||||
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
|
||||
}
|
||||
|
||||
public IWorkItemResult<TResult> QueueWorkItem<T1, T2, T3, T4, TResult>(
|
||||
Func<T1, T2, T3, T4, TResult> func, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
|
||||
{
|
||||
PreQueueWorkItem();
|
||||
WorkItem workItem = WorkItemFactory.CreateWorkItem(
|
||||
this,
|
||||
WIGStartInfo,
|
||||
state =>
|
||||
{
|
||||
return func.Invoke(arg1, arg2, arg3, arg4);
|
||||
},
|
||||
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3, arg4 } : null);
|
||||
Enqueue(workItem);
|
||||
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+561
@@ -0,0 +1,561 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Amib.Threading.Internal
|
||||
{
|
||||
#region WorkItemsQueue class
|
||||
|
||||
/// <summary>
|
||||
/// WorkItemsQueue class.
|
||||
/// </summary>
|
||||
public class WorkItemsQueue : IDisposable
|
||||
{
|
||||
#region Member variables
|
||||
|
||||
/// <summary>
|
||||
/// Waiters queue (implemented as stack).
|
||||
/// </summary>
|
||||
private readonly WaiterEntry _headWaiterEntry = new();
|
||||
|
||||
/// <summary>
|
||||
/// Waiters count
|
||||
/// </summary>
|
||||
private int _waitersCount = 0;
|
||||
|
||||
/// <summary>
|
||||
/// Work items queue
|
||||
/// </summary>
|
||||
private readonly Queue<WorkItem> _workItems = new();
|
||||
|
||||
/// <summary>
|
||||
/// Indicate that work items are allowed to be queued
|
||||
/// </summary>
|
||||
private bool _isWorkItemsQueueActive = true;
|
||||
|
||||
[ThreadStatic]
|
||||
private static WaiterEntry _waiterEntry;
|
||||
|
||||
/// <summary>
|
||||
/// A flag that indicates if the WorkItemsQueue has been disposed.
|
||||
/// </summary>
|
||||
private bool _isDisposed = false;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public properties
|
||||
|
||||
/// <summary>
|
||||
/// Returns the current number of work items in the queue
|
||||
/// </summary>
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
return _workItems.Count;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the current number of waiters
|
||||
/// </summary>
|
||||
public int WaitersCount
|
||||
{
|
||||
get
|
||||
{
|
||||
return _waitersCount;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public methods
|
||||
|
||||
/// <summary>
|
||||
/// Enqueue a work item to the queue.
|
||||
/// </summary>
|
||||
public bool EnqueueWorkItem(WorkItem workItem)
|
||||
{
|
||||
// A work item cannot be null, since null is used in the
|
||||
// WaitForWorkItem() method to indicate timeout or cancel
|
||||
if (workItem is null)
|
||||
{
|
||||
throw new ArgumentNullException("workItem", "workItem cannot be null");
|
||||
}
|
||||
|
||||
// First check if there is a waiter waiting for work item. During
|
||||
// the check, timed out waiters are ignored. If there is no
|
||||
// waiter then the work item is queued.
|
||||
lock (this)
|
||||
{
|
||||
ValidateNotDisposed();
|
||||
|
||||
if (!_isWorkItemsQueueActive)
|
||||
return false;
|
||||
|
||||
while (_waitersCount > 0)
|
||||
{
|
||||
// Dequeue a waiter.
|
||||
WaiterEntry waiterEntry = PopWaiter();
|
||||
|
||||
// Signal the waiter. On success break the loop
|
||||
if (waiterEntry.Signal(workItem))
|
||||
return true;
|
||||
}
|
||||
|
||||
// Enqueue the work item
|
||||
_workItems.Enqueue(workItem);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void CloseThreadWaiter()
|
||||
{
|
||||
if(_waiterEntry is not null)
|
||||
{
|
||||
_waiterEntry.Close();
|
||||
_waiterEntry = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Waits for a work item or exits on timeout or cancel
|
||||
/// </summary>
|
||||
/// <param name="millisecondsTimeout">Timeout in milliseconds</param>
|
||||
/// <param name="cancelEvent">Cancel wait handle</param>
|
||||
/// <returns>Returns true if the resource was granted</returns>
|
||||
public WorkItem DequeueWorkItem( int millisecondsTimeout, WaitHandle cancelEvent)
|
||||
{
|
||||
// This method cause the caller to wait for a work item.
|
||||
// If there is at least one waiting work item then the
|
||||
// method returns immidiately with it.
|
||||
//
|
||||
// If there are no waiting work items then the caller
|
||||
// is queued between other waiters for a work item to arrive.
|
||||
//
|
||||
// If a work item didn't come within millisecondsTimeout or
|
||||
// the user canceled the wait by signaling the cancelEvent
|
||||
// then the method returns null to indicate that the caller
|
||||
// didn't get a work item.
|
||||
|
||||
WaiterEntry waiterEntry;
|
||||
lock (this)
|
||||
{
|
||||
ValidateNotDisposed();
|
||||
|
||||
// If there are waiting work items then take one and return.
|
||||
if (_workItems.Count > 0)
|
||||
return _workItems.Dequeue();
|
||||
|
||||
// No waiting work items ...
|
||||
|
||||
// Get the waiter entry for the waiters queue
|
||||
waiterEntry = GetThreadWaiterEntry();
|
||||
|
||||
// Put the waiter with the other waiters
|
||||
PushWaiter(waiterEntry);
|
||||
}
|
||||
|
||||
// Prepare array of wait handle for the WaitHandle.WaitAny()
|
||||
WaitHandle[] waitHandles = new WaitHandle[] { waiterEntry.WaitHandle, cancelEvent };
|
||||
|
||||
// Wait for an available resource, cancel event, or timeout.
|
||||
|
||||
// During the wait we are supposes to exit the synchronization
|
||||
// domain. (Placing true as the third argument of the WaitAny())
|
||||
// It just doesn't work, I don't know why, so I have two lock(this)
|
||||
// statments instead of one.
|
||||
|
||||
int index = STPEventWaitHandle.WaitAny( waitHandles, millisecondsTimeout, true);
|
||||
|
||||
lock (this)
|
||||
{
|
||||
// On timeout update the waiterEntry that it is timed out
|
||||
if (index != 0)
|
||||
{
|
||||
// The Timeout() fails if the waiter has already been signaled
|
||||
// On timeout remove the waiter from the queue.
|
||||
// Note that the complexity is O(1).
|
||||
if (waiterEntry.Timeout())
|
||||
{
|
||||
RemoveWaiter(waiterEntry, false);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// On success return the work item
|
||||
WorkItem workItem = waiterEntry.WorkItem;
|
||||
workItem ??= _workItems.Dequeue();
|
||||
|
||||
return workItem;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cleanup the work items queue, hence no more work
|
||||
/// items are allowed to be queue
|
||||
/// </summary>
|
||||
private void Cleanup()
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
// Deactivate only once
|
||||
if (!_isWorkItemsQueueActive)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't queue more work items
|
||||
_isWorkItemsQueueActive = false;
|
||||
|
||||
foreach (WorkItem workItem in _workItems)
|
||||
{
|
||||
workItem.DisposeOfState();
|
||||
}
|
||||
|
||||
// Clear the work items that are already queued
|
||||
_workItems.Clear();
|
||||
|
||||
// Note:
|
||||
// I don't iterate over the queue and dispose of work items's states,
|
||||
// since if a work item has a state object that is still in use in the
|
||||
// application then I must not dispose it.
|
||||
|
||||
// Tell the waiters that they were timed out.
|
||||
// It won't signal them to exit, but to ignore their
|
||||
// next work item.
|
||||
while (_waitersCount > 0)
|
||||
{
|
||||
WaiterEntry waiterEntry = PopWaiter();
|
||||
waiterEntry.Timeout();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public object[] GetStates()
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
object[] states = new object[_workItems.Count];
|
||||
int i = 0;
|
||||
foreach (WorkItem workItem in _workItems)
|
||||
{
|
||||
states[i] = workItem.GetWorkItemResult().State;
|
||||
++i;
|
||||
}
|
||||
return states;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private methods
|
||||
|
||||
/// <summary>
|
||||
/// Returns the WaiterEntry of the current thread
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
/// In order to avoid creation and destuction of WaiterEntry
|
||||
/// objects each thread has its own WaiterEntry object.
|
||||
private static WaiterEntry GetThreadWaiterEntry()
|
||||
{
|
||||
if (_waiterEntry is null)
|
||||
{
|
||||
_waiterEntry = new WaiterEntry();
|
||||
}
|
||||
else
|
||||
_waiterEntry.Reset();
|
||||
return _waiterEntry;
|
||||
}
|
||||
|
||||
#region Waiters stack methods
|
||||
|
||||
/// <summary>
|
||||
/// Push a new waiter into the waiter's stack
|
||||
/// </summary>
|
||||
/// <param name="newWaiterEntry">A waiter to put in the stack</param>
|
||||
public void PushWaiter(WaiterEntry newWaiterEntry)
|
||||
{
|
||||
// Remove the waiter if it is already in the stack and
|
||||
// update waiter's count as needed
|
||||
RemoveWaiter(newWaiterEntry, false);
|
||||
|
||||
// If the stack is empty then newWaiterEntry is the new head of the stack
|
||||
if (_headWaiterEntry._nextWaiterEntry is null)
|
||||
{
|
||||
_headWaiterEntry._nextWaiterEntry = newWaiterEntry;
|
||||
newWaiterEntry._prevWaiterEntry = _headWaiterEntry;
|
||||
}
|
||||
// If the stack is not empty then put newWaiterEntry as the new head
|
||||
// of the stack.
|
||||
else
|
||||
{
|
||||
// Save the old first waiter entry
|
||||
WaiterEntry oldFirstWaiterEntry = _headWaiterEntry._nextWaiterEntry;
|
||||
|
||||
// Update the links
|
||||
_headWaiterEntry._nextWaiterEntry = newWaiterEntry;
|
||||
newWaiterEntry._nextWaiterEntry = oldFirstWaiterEntry;
|
||||
newWaiterEntry._prevWaiterEntry = _headWaiterEntry;
|
||||
oldFirstWaiterEntry._prevWaiterEntry = newWaiterEntry;
|
||||
}
|
||||
|
||||
// Increment the number of waiters
|
||||
++_waitersCount;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pop a waiter from the waiter's stack
|
||||
/// </summary>
|
||||
/// <returns>Returns the first waiter in the stack</returns>
|
||||
private WaiterEntry PopWaiter()
|
||||
{
|
||||
// Store the current stack head
|
||||
WaiterEntry oldFirstWaiterEntry = _headWaiterEntry._nextWaiterEntry;
|
||||
|
||||
// Store the new stack head
|
||||
WaiterEntry newHeadWaiterEntry = oldFirstWaiterEntry._nextWaiterEntry;
|
||||
|
||||
// Update the old stack head list links and decrement the number
|
||||
// waiters.
|
||||
RemoveWaiter(oldFirstWaiterEntry, true);
|
||||
|
||||
// Update the new stack head
|
||||
_headWaiterEntry._nextWaiterEntry = newHeadWaiterEntry;
|
||||
if (newHeadWaiterEntry is not null)
|
||||
{
|
||||
newHeadWaiterEntry._prevWaiterEntry = _headWaiterEntry;
|
||||
}
|
||||
|
||||
// Return the old stack head
|
||||
return oldFirstWaiterEntry;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remove a waiter from the stack
|
||||
/// </summary>
|
||||
/// <param name="waiterEntry">A waiter entry to remove</param>
|
||||
/// <param name="popDecrement">If true the waiter count is always decremented</param>
|
||||
private void RemoveWaiter(WaiterEntry waiterEntry, bool popDecrement)
|
||||
{
|
||||
// Store the prev entry in the list
|
||||
WaiterEntry prevWaiterEntry = waiterEntry._prevWaiterEntry;
|
||||
waiterEntry._prevWaiterEntry = null;
|
||||
|
||||
// Store the next entry in the list
|
||||
WaiterEntry nextWaiterEntry = waiterEntry._nextWaiterEntry;
|
||||
waiterEntry._nextWaiterEntry = null;
|
||||
|
||||
// popDecrement indicate if we need to decrement the waiters count.
|
||||
// If we got here from PopWaiter then we must decrement.
|
||||
// If we got here from PushWaiter then we decrement only if
|
||||
// the waiter was already in the stack.
|
||||
|
||||
// If the waiter entry had a prev link then update it.
|
||||
// It also means that the waiter is already in the list and we
|
||||
// need to decrement the waiters count.
|
||||
if (prevWaiterEntry is not null)
|
||||
{
|
||||
prevWaiterEntry._nextWaiterEntry = nextWaiterEntry;
|
||||
popDecrement = true;
|
||||
}
|
||||
|
||||
// If the waiter entry had a next link then update it.
|
||||
// It also means that the waiter is already in the list and we
|
||||
// need to decrement the waiters count.
|
||||
if (nextWaiterEntry is not null)
|
||||
{
|
||||
nextWaiterEntry._prevWaiterEntry = prevWaiterEntry;
|
||||
popDecrement = true;
|
||||
}
|
||||
|
||||
// Decrement the waiters count if needed
|
||||
if (popDecrement)
|
||||
--_waitersCount;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
|
||||
#region WaiterEntry class
|
||||
|
||||
// A waiter entry in the _waiters queue.
|
||||
public sealed class WaiterEntry : IDisposable
|
||||
{
|
||||
#region Member variables
|
||||
|
||||
/// <summary>
|
||||
/// Event to signal the waiter that it got the work item.
|
||||
/// </summary>
|
||||
private AutoResetEvent _waitHandle = new(false);
|
||||
|
||||
/// <summary>
|
||||
/// Flag to know if this waiter already quited from the queue
|
||||
/// because of a timeout.
|
||||
/// </summary>
|
||||
private bool _isTimedout = false;
|
||||
|
||||
/// <summary>
|
||||
/// Flag to know if the waiter was signaled and got a work item.
|
||||
/// </summary>
|
||||
private bool _isSignaled = false;
|
||||
|
||||
/// <summary>
|
||||
/// A work item that passed directly to the waiter withou going
|
||||
/// through the queue
|
||||
/// </summary>
|
||||
private WorkItem _workItem = null;
|
||||
|
||||
private bool _isDisposed = false;
|
||||
|
||||
// Linked list members
|
||||
internal WaiterEntry _nextWaiterEntry = null;
|
||||
internal WaiterEntry _prevWaiterEntry = null;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Construction
|
||||
|
||||
public WaiterEntry()
|
||||
{
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public methods
|
||||
|
||||
public WaitHandle WaitHandle
|
||||
{
|
||||
get { return _waitHandle; }
|
||||
}
|
||||
|
||||
public WorkItem WorkItem
|
||||
{
|
||||
get
|
||||
{
|
||||
return _workItem;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Signal the waiter that it got a work item.
|
||||
/// </summary>
|
||||
/// <returns>Return true on success</returns>
|
||||
/// The method fails if Timeout() preceded its call
|
||||
public bool Signal(WorkItem workItem)
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
if (_isTimedout)
|
||||
return false;
|
||||
|
||||
_workItem = workItem;
|
||||
_isSignaled = true;
|
||||
_waitHandle.Set();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mark the wait entry that it has been timed out
|
||||
/// </summary>
|
||||
/// <returns>Return true on success</returns>
|
||||
/// The method fails if Signal() preceded its call
|
||||
public bool Timeout()
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
// Time out can happen only if the waiter wasn't marked as
|
||||
// signaled
|
||||
if (_isSignaled)
|
||||
return false;
|
||||
|
||||
// We don't remove the waiter from the queue, the DequeueWorkItem
|
||||
// method skips _waiters that were timed out.
|
||||
_isTimedout = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reset the wait entry so it can be used again
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
_workItem = null;
|
||||
_isTimedout = false;
|
||||
_isSignaled = false;
|
||||
_waitHandle.Reset();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Free resources
|
||||
/// </summary>
|
||||
public void Close()
|
||||
{
|
||||
_workItem = null;
|
||||
if (_waitHandle is not null)
|
||||
{
|
||||
_waitHandle.Close();
|
||||
_waitHandle = null;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IDisposable Members
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
if (!_isDisposed)
|
||||
{
|
||||
Close();
|
||||
_isDisposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IDisposable Members
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!_isDisposed)
|
||||
{
|
||||
_isDisposed = true;
|
||||
Cleanup();
|
||||
_headWaiterEntry.Close();
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void ValidateNotDisposed()
|
||||
{
|
||||
if (_isDisposed)
|
||||
{
|
||||
throw new ObjectDisposedException(GetType().ToString(), "The SmartThreadPool has been shutdown");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user