/// <summary> /// 异步调用助手类 /// </summary> /// <see cref="http://www.tuicool.com/articles/QF73qaA"/> public static class AsyncHelper { public static void InvokeAndWait(Func<Task> asyncMethod) { // ReSharper disable once ConvertClosureToMethodGroup Task.Run(() => asyncMethod()) .ContinueWith(t => t.Wait()) .Wait(); } public static T InvokeAndWait<T>(Func<Task<T>> asyncMethod) { var result = default(T); // ReSharper disable once ConvertClosureToMethodGroup Task.Run<T>(() => asyncMethod()) .ContinueWith(t => { t.Wait(); result = t.Result; }).Wait(); return result; } }
/// <summary> /// 异步调用助手类 /// https://github.com/aspnet/AspNetIdentity.git /// </summary> public static class TaskAsyncHelper { private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default); /// <summary> /// demo: return TaskAsyncHelper.RunSync(() => manager.UpdateAsync(role)); /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="func"></param> /// <returns></returns> public static TResult RunSync<TResult>(Func<Task<TResult>> func) { var cultureUi = CultureInfo.CurrentUICulture; var culture = CultureInfo.CurrentCulture; return _myTaskFactory.StartNew(() => { Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = cultureUi; return func(); }).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// demo: TaskAsyncHelper.RunSync(() => manager.SendEmailAsync(userId, subject, body)); /// </summary> /// <param name="func"></param> public static void RunSync(Func<Task> func) { var cultureUi = CultureInfo.CurrentUICulture; var culture = CultureInfo.CurrentCulture; _myTaskFactory.StartNew(() => { Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = cultureUi; return func(); }).Unwrap().GetAwaiter().GetResult(); } }