// Raises the PostCompleted event. protected virtual void OnPostCompleted(PostCompletedEventArgs e) { EventHandler <PostCompletedEventArgs> handler = PostCompleted; if (handler != null) { context.Post(delegate(object state) { handler(this, e); }, null); } }
// Processes and invokes delegates. private void DelegateProcedure() { lock (lockObject) { // Signal the constructor that the thread is now running. Monitor.Pulse(lockObject); } // Set this DelegateQueue as the SynchronizationContext for this thread. SynchronizationContext.SetSynchronizationContext(this); // Placeholder for DelegateQueueAsyncResult objects. DelegateQueueAsyncResult result = null; // While the DelegateQueue has not been disposed. while (true) { // Critical section. lock (lockObject) { // If the DelegateQueue has been disposed, break out of loop; we're done. if (disposed) { break; } // If there are delegates waiting to be invoked. if (delegateDeque.Count > 0) { result = delegateDeque.PopFront(); } // Else there are no delegates waiting to be invoked. else { // Wait for next delegate. Monitor.Wait(lockObject); // If the DelegateQueue has been disposed, break out of loop; we're done. if (disposed) { break; } Debug.Assert(delegateDeque.Count > 0); result = delegateDeque.PopFront(); } } Debug.Assert(result != null); // Invoke the delegate. result.Invoke(); if (result.NotificationType == NotificationType.BeginInvokeCompleted) { InvokeCompletedEventArgs e = new InvokeCompletedEventArgs( result.Method, result.GetArgs(), result.ReturnValue, result.Error); OnInvokeCompleted(e); } else if (result.NotificationType == NotificationType.PostCompleted) { object[] args = result.GetArgs(); Debug.Assert(args.Length == 1); Debug.Assert(result.Method is SendOrPostCallback); PostCompletedEventArgs e = new PostCompletedEventArgs( (SendOrPostCallback)result.Method, result.Error, args[0]); OnPostCompleted(e); } else { Debug.Assert(result.NotificationType == NotificationType.None); } } Debug.WriteLine(delegateThread.Name + " Finished"); }