view Implab/Parallels/AsyncPool.cs @ 33:b255e4aeef17

removed the reference to the parent from the promise object this allows resolved promises to release parents and results they are holding. Added complete set of operations to IPromiseBase interface Subscribing to the cancellation event of the promise should not affect it's IsExclusive property More tests.
author cin
date Thu, 10 Apr 2014 02:39:29 +0400
parents 9bf5b23650c9
children 2880242f987a
line wrap: on
line source

using System;
using System.Threading;

namespace Implab.Parallels {
	/// <summary>
	/// Класс для распаралеливания задач.
	/// </summary>
	/// <remarks>
	/// Используя данный класс и лямда выражения можно распараллелить
	/// вычисления, для этого используется концепция обещаний.
	/// </remarks>
	public static class AsyncPool {

		public static Promise<T> Invoke<T>(Func<T> func) {
			var p = new Promise<T>();

			ThreadPool.QueueUserWorkItem(param => {
				try {
					p.Resolve(func());
				} catch(Exception e) {
					p.Reject(e);
				}
			});

			return p;
		}

        public static Promise<T> InvokeNewThread<T>(Func<T> func) {
            var p = new Promise<T>();

            var worker = new Thread(() => {
                try {
                    p.Resolve(func());
                } catch (Exception e) {
                    p.Reject(e);
                }
            });
            worker.IsBackground = true;
            worker.Start();

            return p;
        }
	}
}