private AsyncResult opAR; // The async result for the operation /// <summary> /// Constructs a work thread. /// </summary> public WorkerThread() { this.waitEvent = new AutoResetEvent(true); this.wakeEvent = new AutoResetEvent(false); this.method = null; this.arg = null; this.opAR = null; this.thread = new Thread(new ThreadStart(ThreadLoop)); this.thread.Start(); }
/// <summary> /// Invokes a method on the worker thread, blocking the current thread /// until any operation already in progress complete. Once the operation /// has been successfully submitted to the thread, this method will return /// to allow the operation to complete asynchronously. /// </summary> /// <param name="method">The method delegate.</param> /// <param name="arg">The method parameter.</param> /// <param name="callback">The delegate to be called when the timer fires (or <c>null</c>).</param> /// <param name="state">Application specific state.</param> /// <returns>The <see cref="IAsyncResult" /> instance to be used to track the operation.</returns> public IAsyncResult BeginInvoke(WorkerThreadMethod method, object arg, AsyncCallback callback, object state) { if (thread == null) { throw new InvalidOperationException("WorkerThread is closed."); } waitEvent.WaitOne(); this.method = method; this.arg = arg; this.opAR = new AsyncResult(null, callback, state); this.opAR.Started(); wakeEvent.Set(); return(this.opAR); }
/// <summary> /// Invokes a method on the worker thread, blocking the current thread /// until the operation completes. /// </summary> /// <param name="method">The method delegate.</param> /// <param name="arg">The method parameter.</param> /// <returns>The result returned by the delegate call.</returns> /// <remarks> /// <note> /// Exceptions thrown in the method call on the worker thread /// will be caught and rethrown on this thread. /// </note> /// </remarks> public object Invoke(WorkerThreadMethod method, object arg) { var ar = BeginInvoke(method, arg, null, null); return(EndInvoke(ar)); }