35
|
1 using Implab.Diagnostics;
|
25
|
2 using System;
|
|
3 using System.Threading;
|
|
4
|
|
5 namespace Implab.Parallels {
|
|
6 /// <summary>
|
|
7 /// Класс для распаралеливания задач.
|
|
8 /// </summary>
|
|
9 /// <remarks>
|
|
10 /// Используя данный класс и лямда выражения можно распараллелить
|
|
11 /// вычисления, для этого используется концепция обещаний.
|
|
12 /// </remarks>
|
|
13 public static class AsyncPool {
|
|
14
|
45
|
15 public static IPromise<T> Invoke<T>(Func<T> func) {
|
25
|
16 var p = new Promise<T>();
|
92
|
17 var caller = TraceContext.Instance.CurrentOperation;
|
25
|
18
|
|
19 ThreadPool.QueueUserWorkItem(param => {
|
92
|
20 TraceContext.Instance.EnterLogicalOperation(caller,false);
|
25
|
21 try {
|
14
|
22 p.Resolve(func());
|
25
|
23 } catch(Exception e) {
|
|
24 p.Reject(e);
|
92
|
25 } finally {
|
|
26 TraceContext.Instance.Leave();
|
|
27 }
|
25
|
28 });
|
|
29
|
|
30 return p;
|
14
|
31 }
|
|
32
|
45
|
33 public static IPromise<T> InvokeNewThread<T>(Func<T> func) {
|
14
|
34 var p = new Promise<T>();
|
|
35
|
92
|
36 var caller = TraceContext.Instance.CurrentOperation;
|
35
|
37
|
14
|
38 var worker = new Thread(() => {
|
92
|
39 TraceContext.Instance.EnterLogicalOperation(caller,false);
|
14
|
40 try {
|
|
41 p.Resolve(func());
|
|
42 } catch (Exception e) {
|
|
43 p.Reject(e);
|
92
|
44 } finally {
|
|
45 TraceContext.Instance.Leave();
|
14
|
46 }
|
|
47 });
|
|
48 worker.IsBackground = true;
|
|
49 worker.Start();
|
|
50
|
|
51 return p;
|
25
|
52 }
|
48
|
53
|
|
54
|
66
|
55 public static IPromise InvokeNewThread(Action func) {
|
48
|
56 var p = new Promise<object>();
|
|
57
|
92
|
58 var caller = TraceContext.Instance.CurrentOperation;
|
48
|
59
|
|
60 var worker = new Thread(() => {
|
92
|
61 TraceContext.Instance.EnterLogicalOperation(caller,false);
|
48
|
62 try {
|
|
63 func();
|
|
64 p.Resolve();
|
|
65 } catch (Exception e) {
|
|
66 p.Reject(e);
|
92
|
67 } finally {
|
|
68 TraceContext.Instance.Leave();
|
48
|
69 }
|
|
70 });
|
|
71 worker.IsBackground = true;
|
|
72 worker.Start();
|
|
73
|
|
74 return p;
|
|
75 }
|
25
|
76 }
|
|
77 }
|