view Implab.Fx/PromiseHelpers.cs @ 187:dd4a3590f9c6 ref20160224

Reworked cancelation handling, if the cancel handler isn't specified the OperationCanceledException will be handled by the error handler Any unhandled OperationCanceledException will cause the promise cancelation
author cin
date Tue, 19 Apr 2016 17:35:20 +0300
parents 2573b562e328
children
line wrap: on
line source

using System;
using System.Windows.Forms;
using System.Threading;

namespace Implab.Fx
{
    public static class PromiseHelpers
    {
        /// <summary>
        /// Перенаправляет обработку обещания в поток указанного элемента управления.
        /// </summary>
        /// <typeparam name="T">Тип результата обещания</typeparam>
        /// <param name="that">Исходное обещание</param>
        /// <param name="ctl">Элемент управления</param>
        /// <returns>Новое обещание, обработчики которого будут выполнены в потоке элемента управления.</returns>
        /// <exception cref="ArgumentNullException">Параметр не может быть <c>null</c>.</exception>
        /// <example>
        /// client
        ///     .Get("description.txt") // returns a promise
        ///     .DispatchToControl(m_ctl) // handle the promise in the thread of the control
        ///     .Then(
        ///         description => m_ctl.Text = description // now it's safe
        ///     )
        /// </example>
        public static IPromise<T> DispatchToControl<T>(this IPromise<T> that, Control ctl)
        {
            Safe.ArgumentNotNull(that, "that");
            Safe.ArgumentNotNull(ctl, "ctl");

            var directed = new ControlBoundPromise<T>(ctl);

            directed.On(that.Cancel, PromiseEventType.Cancelled);

            that.On(
                directed.Resolve,
                directed.Reject,
                directed.Cancel
            );

            return directed;
        }
    }
}