Exemple #1
0
        /// <summary>
        /// Invoke in specific tread synchronously and return result or throw
        /// exception to calling (not specific) thread.
        /// </summary>
        public TResult Invoke <TResult>(Func <TResult> func)
        {
            var       res           = default(TResult);
            Exception origException = null;

            _invoker.Invoke(() =>
            {
                try
                {
                    res = func();
                }
                catch (Exception ex)
                {
                    origException = ex;
                }
            });

            if (origException == null)
            {
                return(res);
            }
            else
            {
                var exToThrow = new ThreadSyncException(origException);
#if DEBUG
                Debug.WriteLine(exToThrow.ToString());
#endif
                throw exToThrow;
            }
        }
Exemple #2
0
        /// <summary>
        /// Invoke in specific tread asynchronously.
        /// </summary>
        public async Task <TResult> InvokeAsync <TResult>(Func <Task <TResult> > func)
        {
            var tcs = new TaskCompletionSource <TResult>(TaskCreationOptions.RunContinuationsAsynchronously);

            _invoker.InvokeAsync(async() =>
            {
                try
                {
                    var res = await func();
                    tcs.SetResult(res);
                }
                catch (Exception ex)
                {
                    var exToThrow = new ThreadSyncException(ex);
#if DEBUG
                    Debug.WriteLine(exToThrow.ToString());
#endif
                    tcs.SetException(exToThrow);
                }
            });
            return(await tcs.Task);
        }