|
|
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.Snapshot();
|
|
|
|
|
|
ThreadPool.QueueUserWorkItem(param => {
|
|
|
TraceContext.Fork(caller);
|
|
|
try {
|
|
|
p.Resolve(func());
|
|
|
} catch(Exception e) {
|
|
|
p.Reject(e);
|
|
|
}
|
|
|
});
|
|
|
|
|
|
return p;
|
|
|
}
|
|
|
|
|
|
public static IPromise<T> InvokeNewThread<T>(Func<T> func) {
|
|
|
var p = new Promise<T>();
|
|
|
|
|
|
var caller = TraceContext.Snapshot();
|
|
|
|
|
|
var worker = new Thread(() => {
|
|
|
TraceContext.Fork(caller);
|
|
|
try {
|
|
|
p.Resolve(func());
|
|
|
} catch (Exception e) {
|
|
|
p.Reject(e);
|
|
|
}
|
|
|
});
|
|
|
worker.IsBackground = true;
|
|
|
worker.Start();
|
|
|
|
|
|
return p;
|
|
|
}
|
|
|
|
|
|
|
|
|
public static IPromise InvokeNewThread(Action func) {
|
|
|
var p = new Promise<object>();
|
|
|
|
|
|
var caller = TraceContext.Snapshot();
|
|
|
|
|
|
var worker = new Thread(() => {
|
|
|
TraceContext.Fork(caller);
|
|
|
try {
|
|
|
func();
|
|
|
p.Resolve();
|
|
|
} catch (Exception e) {
|
|
|
p.Reject(e);
|
|
|
}
|
|
|
});
|
|
|
worker.IsBackground = true;
|
|
|
worker.Start();
|
|
|
|
|
|
return p;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|