Example #1
0
        /// <summary>
        /// Executes a "Func" delegate as a thread. This method provides 1 input parameter
        /// to the "Func", executes the thread code and DOES NOT wait for the thread to end.
        /// The return value from the thread can be read using the "Result" extention method
        /// </summary>
        /// <typeparam name="T">Input data is of type T</typeparam>
        /// <typeparam name="R">Reponse data is of type R</typeparam>
        /// <param name="ThreadFunctionDelegate">A delegate of type Func<T,R> </param>
        /// <param name="ParameterInputData">Parameter data for use by the ThreadFunctionDelegate</param>
        /// <returns>Response data from the thread (of type R)</returns>
        public static ThreadResult <R> Run <T, R>(this Func <T, R> ThreadFunctionDelegate, T ParameterInputData)
        {
            AutoResetEvent WaitHandle = new AutoResetEvent(false);

            // Start the thread and execute the code
            Thread t = new Thread(new ParameterizedThreadStart(ThreadHostWrapper <T, R>));

            t.IsBackground = true;
            ThreadFunctionData <T, R> data = new ThreadFunctionData <T, R> {
                ThreadFunctionDelegate = ThreadFunctionDelegate, WaitHandle = WaitHandle, ParameterInputData = ParameterInputData, ResponseData = default(R)
            };

            t.Start(data);

            return(data);
        }
Example #2
0
        /// <summary>
        /// Executes a "Func" delegate as a thread. This method provides 1 input parameter
        /// to the "Func", executes the thread code and waits for the thread to end. It then
        /// returns the response data from the thread.
        /// </summary>
        /// <typeparam name="T">Input data is of type T</typeparam>
        /// <typeparam name="R">Reponse data is of type R</typeparam>
        /// <param name="ThreadFunctionDelegate">A delegate of type Func<T,R> </param>
        /// <param name="ParameterInputData">Parameter data for use by the ThreadFunctionDelegate</param>
        /// <returns>Response data from the thread (of type R)</returns>
        public static R RunToCompletion <T, R>(Func <T, R> ThreadFunctionDelegate, T ParameterInputData)
        {
            AutoResetEvent WaitHandle = new AutoResetEvent(false);

            // Start the thread and execute the code
            Thread t = new Thread(new ParameterizedThreadStart(ThreadHostWrapper <T, R>));

            t.IsBackground = true;
            ThreadFunctionData <T, R> retVal = new ThreadFunctionData <T, R> {
                ThreadFunctionDelegate = ThreadFunctionDelegate, WaitHandle = WaitHandle, ParameterInputData = ParameterInputData, ResponseData = default(R)
            };

            t.Start(retVal);

            // Wait till thread signals that it has completed the operation
            WaitHandle.WaitOne();

            return(retVal.ResponseData);
        }