コード例 #1
0
        /// <summary>
        /// 同步转异步方法
        /// </summary>
        /// <typeparam name="T">返回值参数</typeparam>
        /// <param name="funcAction">方法调用</param>
        /// <param name="callBackAction">回调</param>
        public static void DoAsync <T>(Func <T> funcAction, Action <AsyncEventArgs <T> > callBackAction = null)
        {
            TaskScheduler syncContextScheduler = TaskScheduler.FromCurrentSynchronizationContext();

            Task.Factory.StartNew <T>(funcAction, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).ContinueWith((ee) =>
            {
                var ex = ee.Exception != null ? ee.Exception.InnerException : null;

                T result = default(T);
                if (ex == null && ee.Result != null)
                {
                    result = (T)ee.Result;
                }

                AsyncEventArgs <T> args = new AsyncEventArgs <T>(ex, ee.IsCanceled, null, result);
                if (callBackAction != null)
                {
                    callBackAction(args);
                }
            }, syncContextScheduler);
        }