AccidentalFish.ApplicationSupport.Core.Threading.AsyncPump.Run C# (CSharp) Method

Run() public static method

Runs the specified asynchronous function.
public static Run ( Func func ) : void
func Func The asynchronous function to execute.
return void
        public static void Run(Func<Task> func)
        {
            if (func == null) throw new ArgumentNullException(nameof(func));

            var prevCtx = SynchronizationContext.Current;
            try
            {
                // Establish the new context
                var syncCtx = new SingleThreadSynchronizationContext();
                SynchronizationContext.SetSynchronizationContext(syncCtx);

                // Invoke the function and alert the context to when it completes
                var t = func();
                if (t == null) throw new InvalidOperationException("No task provided.");
                t.ContinueWith(delegate { syncCtx.Complete(); }, TaskScheduler.Default);

                // Pump continuations and propagate any exceptions
                syncCtx.RunOnCurrentThread();
                t.GetAwaiter().GetResult();
            }
            finally { SynchronizationContext.SetSynchronizationContext(prevCtx); }
        }
AsyncPump