Exemple #1
0
        /// <summary>
        /// Starts the invocation of a delegate synchronized by the <see cref="SynchronizationContext"/> of the thread that created this <see cref="GenericSynchronizingObject"/>. A corresponding call to <see cref="EndInvoke"/> is not required.
        /// </summary>
        /// <param name="method">The delegate to run. May not be <c>null</c>.</param>
        /// <param name="args">The arguments to pass to <paramref name="method"/>. May be <c>null</c> if the delegate does not require arguments.</param>
        /// <returns>An <see cref="IAsyncResult"/> that can be used to detect completion of the delegate.</returns>
        /// <remarks>
        /// <para>If the <see cref="SynchronizationContext.Post"/> for this object's synchronization context is reentrant, then this method is also reentrant.</para>
        /// </remarks>
        public IAsyncResult BeginInvoke(Delegate method, object[] args)
        {
            Contract.Ensures(Contract.Result <IAsyncResult>() != null);
            Contract.Assume(method != null);

            // (This method may be invoked from any thread)
            IAsyncResult ret = new AsyncResult();

            // (The delegate passed to Post will run in the thread chosen by the SynchronizationContext)
            this.synchronizationContext.Post(
                (SendOrPostCallback) delegate(object state)
            {
                AsyncResult result = (AsyncResult)state;
                try
                {
                    result.ReturnValue = method.DynamicInvoke(args);
                }
                catch (Exception ex)
                {
                    result.Error = ex;
                }

                result.Done();
            },
                ret);
            return(ret);
        }