Example #1
0
        /// <summary>
        ///     Queues the operation for execution on the main thread and waits until it has completed
        /// </summary>
        /// <remarks>
        ///     If an exception occurs during the processing of the function the event will be re-thrown by this function for you
        ///     to handle.
        /// </remarks>
        /// <typeparam name="T">The result of the function</typeparam>
        /// <param name="function">The function to execute.</param>
        /// <returns>The result of the function executed.</returns>
        /// <exception cref="DispatcherException">Thrown if an unhandled exception was raised while executing the dispatcher task.</exception>
        public T InvokeWait <T>(Func <T> function)
        {
            //Invoke async and wait for it.
            using (FunctionDispatcherTask <T> task = InvokeAsync(function))
            {
                task.WaitHandle.WaitOne();

                if (task.TaskState == DispatcherTaskState.Failed)
                {
                    throw new DispatcherException("An unhandled exception was thrown inside the dispatcher task, see inner exception for more details.", task.Exception);
                }
                else
                {
                    return(task.Result);
                }
            }
        }
Example #2
0
        /// <summary>
        ///     Queues the operation for execution on the main thread.
        /// </summary>
        /// <typeparam name="T">The type to return.</typeparam>
        /// <param name="function">The function to execute.</param>
        /// <param name="callback">The callback to invoke once this is complete.</param>
        /// <returns>A DispatcherTask for this operation.</returns>
        /// <remarks>
        ///     This returns an IDisposable object, it is your responsibility to dispose of it when you're done!
        /// </remarks>
        /// <exception cref="DispatcherException">Thrown if an unhandled exception was raised while executing the dispatcher task when completing synchronously.</exception>
        public FunctionDispatcherTask <T> InvokeAsync <T>(Func <T> function, FunctionDispatchCompleteCallback <T> callback)
        {
            //Queue the operation and wait.
            FunctionDispatcherTask <T> task = new FunctionDispatcherTask <T>(function, callback);

            //Complete synchronously if already executor thread
            if (Thread.CurrentThread.ManagedThreadId == executorThreadID)
            {
                task.Execute(true);
            }
            else
            {
                lock (tasks)
                    tasks.Enqueue(task);

                jobMutex.Set();
            }

            return(task);
        }