/// <summary> /// Adds a new work item /// </summary> /// <param name="method">The method that represents the work to perform</param> /// <param name="parameter">Parameter to pass to the work method</param> /// <returns>An object that can be used to retrieve the result after completion</returns> public WorkloadInfo <TParam, TResult> AddWorkItem(Action <TParam, WorkloadInfo <TParam, TResult> > method, TParam parameter) { var work = new WorkloadInfo <TParam, TResult>(this, parameter, method); BeginWorkItem(work); return(work); }
/// <summary> /// Schedules a work item to begin /// </summary> /// <param name="work">The work to perform</param> /// <remarks>The worker thread is blocked on the startEvent so that the work /// doesn't complete before the client is ready to handle the completion event /// </remarks> void BeginWorkItem(WorkloadInfo <TParam, TResult> work) { lock (this) { outstandingItems++; } ThreadPool.QueueUserWorkItem(delegate { // Wait until it's OK to start startEvent.WaitOne(); try { // Method is responsible for completing itself if it didn't fail work.Method(work.Parameter, work); } catch (Exception ex) { // Complete with a failure case work.NotifyFailure(ex); } }); }