Ejemplo n.º 1
0
        public static InstallerAndRestorer Install()
        {
            // save the values to restore
            var iar = new InstallerAndRestorer();

            iar.originalAutoInstallValue = WindowsFormsSynchronizationContext.AutoInstall;
            iar.originalSyncContext      = SynchronizationContext.Current;
            WindowsFormsSynchronizationContext.AutoInstall = true; // enable autoinstall of the official WinForms context
            iar.tempControl = new Control {
                Visible = false
            };                                                 // create a control, which will cause the WinForms context to become installed
            return(iar);
        }
Ejemplo n.º 2
0
    /// <summary>
    /// Runs the action inside a message loop and continues pumping messages
    /// as long as any asynchronous operations have been registered
    /// </summary>
    public static void Run(Action asyncAction)
    {
        using (InstallerAndRestorer.Install())
        {
            // InstallerAndRestorer ensures the WinForms context is installed
            // capture that WinFormsContext
            var winFormsContext = SynchronizationContext.Current;

            // wrap the WinForms context in our own decorator context and install that
            var asyncVoidContext = new AsyncVoidSyncContext(winFormsContext);
            SynchronizationContext.SetSynchronizationContext(asyncVoidContext);

            // queue up the first message before we start running the loop
            var message = new AsyncActionLaunchMessage(asyncAction, asyncVoidContext);
            asyncVoidContext.Post(message.LaunchMessageImpl, state: null);

            // run the actual WinForms message loop
            Application.Run();
        }
    }
Ejemplo n.º 3
0
    /// <summary>
    /// Runs the function inside a message loop and continues pumping messages
    /// until the returned task completes.
    /// </summary>
    /// <returns>The completed task returned by the delegate's invocation</returns>
    public static Task Run(Func <Task> function)
    {
        using (InstallerAndRestorer.Install())
        {
            // InstallerAndRestorer ensures the WinForms context is installed
            var winFormsContext = SynchronizationContext.Current;

            var message = new TaskFunctionLaunchMessage(function, winFormsContext);

            // queue up our first message before we run the loop
            winFormsContext.Post(message.LaunchMessageImpl, state: null);

            // run the actual WinForms message loop
            Application.Run();

            if (message.ReturnedTask != null)
            {
                message.ReturnedTask.RethrowForCompletedTasks();
            }

            return(message.ReturnedTask);
        }
    }