Mercurial > pub > ImplabNet
view Implab/Parallels/AsyncPool.cs @ 101:279e226dffdd v2
code cleanup
added EnsureDispatched extension
author | cin |
---|---|
date | Thu, 06 Nov 2014 20:03:19 +0300 |
parents | 4c0e5ef99986 |
children | 2573b562e328 |
line wrap: on
line source
using Implab.Diagnostics; using System; using System.Threading; namespace Implab.Parallels { /// <summary> /// Класс для распаралеливания задач. /// </summary> /// <remarks> /// Используя данный класс и лямда выражения можно распараллелить /// вычисления, для этого используется концепция обещаний. /// </remarks> public static class AsyncPool { public static IPromise<T> Invoke<T>(Func<T> func) { var p = new Promise<T>(); var caller = TraceContext.Instance.CurrentOperation; ThreadPool.QueueUserWorkItem(param => { TraceContext.Instance.EnterLogicalOperation(caller,false); try { p.Resolve(func()); } catch(Exception e) { p.Reject(e); } finally { TraceContext.Instance.Leave(); } }); return p; } public static IPromise<T> InvokeNewThread<T>(Func<T> func) { var p = new Promise<T>(); var caller = TraceContext.Instance.CurrentOperation; var worker = new Thread(() => { TraceContext.Instance.EnterLogicalOperation(caller,false); try { p.Resolve(func()); } catch (Exception e) { p.Reject(e); } finally { TraceContext.Instance.Leave(); } }); worker.IsBackground = true; worker.Start(); return p; } public static IPromise InvokeNewThread(Action func) { var p = new Promise<object>(); var caller = TraceContext.Instance.CurrentOperation; var worker = new Thread(() => { TraceContext.Instance.EnterLogicalOperation(caller,false); try { func(); p.Resolve(); } catch (Exception e) { p.Reject(e); } finally { TraceContext.Instance.Leave(); } }); worker.IsBackground = true; worker.Start(); return p; } } }