##// END OF EJS Templates
refactoring, moving to dotnercore, simplifying promises
cin -
r240:fa6cbf4d8841 v3
parent child
Show More
@@ -0,0 +1,39
1 {
2 "version": "0.2.0",
3 "configurations": [
4
5 {
6 "name": "Launch webserver",
7 "type": "mono",
8 "request": "launch",
9 "program": "/usr/lib/mono/4.5/xsp4.exe",
10 "args":[
11 "--root=.",
12 "--port=8081",
13 "-v",
14 "--printlog"
15 ],
16 "preLaunchTask": "build",
17 "cwd": "${workspaceRoot}/Pallada.PoiskAvia.Web",
18 "runtimeExecutable": null,
19 "env": {},
20 "console": "integratedTerminal"
21 },{
22 "name": "Launch model tests",
23 "type": "mono",
24 "request": "launch",
25 "program": "${env:HOME}/.nuget/packages/nunit.consolerunner/3.7.0/tools/nunit3-console.exe",
26 "args": [
27 "${workspaceRoot}/Pallada.PoiskAvia.Model.Test/bin/Debug/net45/Pallada.PoiskAvia.Model.Test.mono.dll",
28 "--where=\"cat==Debug\"",
29 "--labels='On'",
30 "--inprocess",
31 "--workers=1"
32 ],
33 "preLaunchTask": "build",
34 "console": "internalConsole",
35 "internalConsoleOptions": "openOnSessionStart",
36 "cwd": "${workspaceRoot}/Pallada.PoiskAvia.Model.Test/"
37 }
38 ]
39 } No newline at end of file
@@ -0,0 +1,13
1 // Поместите параметры в этот файл, чтобы перезаписать параметры по умолчанию и пользовательские параметры.
2 {
3 "files.exclude": {
4 "**/.git": true,
5 "**/.svn": true,
6 "**/.hg": true,
7 "**/CVS": true,
8 "**/.DS_Store": true,
9 "**/bin": true,
10 "**/obj": true
11 },
12 "omnisharp.useMono": true
13 } No newline at end of file
@@ -0,0 +1,55
1 {
2 // See https://go.microsoft.com/fwlink/?LinkId=733558
3 // for the documentation about the tasks.json format
4 "version": "0.1.0",
5 "command": "msbuild",
6 "args": [
7 // Ask msbuild to generate full paths for file names.
8 "/property:GenerateFullPaths=true"
9 ],
10 "taskSelector": "/t:",
11 "showOutput": "silent",
12 "tasks": [
13 {
14 "taskName": "build",
15 "suppressTaskName": true,
16 // Show the output window only if unrecognized errors occur.
17 "showOutput": "always",
18 // Use the standard MS compiler pattern to detect errors, warnings and infos
19 "problemMatcher": "$msCompile",
20
21 "args" : [
22 "/t:restore;build",
23 "/p:Configuration=DebugMono",
24 "Pallada.PoiskAvia.mono.sln"
25 ]
26 },
27 {
28 "taskName": "clean",
29 // Show the output window only if unrecognized errors occur.
30 "showOutput": "always",
31 // Use the standard MS compiler pattern to detect errors, warnings and infos
32 "problemMatcher": "$msCompile",
33
34 "args" : [
35 "/p:Configuration=DebugMono",
36 "Pallada.PoiskAvia.mono.sln"
37 ]
38 },
39 {
40 "taskName": "runtests",
41 "isTestCommand": true,
42 "suppressTaskName": true,
43 // Show the output window only if unrecognized errors occur.
44 "showOutput": "always",
45 // Use the standard MS compiler pattern to detect errors, warnings and infos
46 "problemMatcher": "$msCompile",
47
48 "args" : [
49 "/t:runtests",
50 "/p:Configuration=DebugMono",
51 "Pallada.PoiskAvia.mono.sln"
52 ]
53 }
54 ]
55 } No newline at end of file
@@ -0,0 +1,65
1 using System;
2 using System.Threading;
3 using Implab.Parallels;
4
5 namespace Implab {
6 public class CancellationToken : ICancellationToken {
7 const int CANCEL_NOT_REQUESTED = 0;
8 const int CANCEL_REQUESTING = 1;
9 const int CANCEL_REQUESTED = 2;
10
11 volatile int m_state = CANCEL_NOT_REQUESTED;
12
13 Action<Exception> m_handler;
14
15 Parallels.SimpleAsyncQueue<Action<Exception>> m_handlers;
16
17 public bool IsCancellationRequested {
18 get { return m_state == CANCEL_REQUESTED; }
19 }
20
21 public Exception CancellationReason {
22 get; set;
23 }
24
25 public void CancellationRequested(Action<Exception> handler) {
26 Safe.ArgumentNotNull(handler, nameof(handler));
27 if (IsCancellationRequested) {
28 handler(CancellationReason);
29 } else {
30 EnqueueHandler(handler);
31 if (IsCancellationRequested && TryDequeueHandler(out handler))
32 handler(CancellationReason);
33 }
34 }
35
36 bool TryDequeueHandler(out Action<Exception> handler) {
37 handler = Interlocked.Exchange(ref m_handler, null);
38 if (handler != null)
39 return true;
40 else if (m_handlers != null)
41 return m_handlers.TryDequeue(out handler);
42 else
43 return false;
44 }
45
46 void EnqueueHandler(Action<Exception> handler) {
47 if (Interlocked.CompareExchange(ref m_handler, handler, null) != null) {
48 if (m_handlers == null)
49 // compare-exchange will fprotect from loosing already created queue
50 Interlocked.CompareExchange(ref m_handlers, new SimpleAsyncQueue<Action<Exception>>(), null);
51 m_handlers.Enqueue(handler);
52 }
53 }
54
55 void RequestCancellation(Exception reason) {
56 if (Interlocked.CompareExchange(ref m_state, CANCEL_REQUESTING, CANCEL_NOT_REQUESTED) == CANCEL_NOT_REQUESTED) {
57 if (reason == null)
58 reason = new OperationCanceledException();
59 CancellationReason = reason;
60 m_state = CANCEL_REQUESTED;
61 }
62 }
63
64 }
65 } No newline at end of file
@@ -0,0 +1,189
1 <?xml version="1.0" encoding="utf-8"?>
2 <Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3 <PropertyGroup>
4 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
5 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
6 <ProjectGuid>{F550F1F8-8746-4AD0-9614-855F4C4B7F05}</ProjectGuid>
7 <OutputType>Library</OutputType>
8 <RootNamespace>Implab</RootNamespace>
9 <AssemblyName>Implab</AssemblyName>
10 <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
11 <TargetFrameworkProfile />
12 </PropertyGroup>
13 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
14 <DebugSymbols>true</DebugSymbols>
15 <DebugType>full</DebugType>
16 <Optimize>true</Optimize>
17 <OutputPath>bin\Debug</OutputPath>
18 <DefineConstants>TRACE;DEBUG;NET_4_5</DefineConstants>
19 <ErrorReport>prompt</ErrorReport>
20 <WarningLevel>4</WarningLevel>
21 <ConsolePause>false</ConsolePause>
22 <RunCodeAnalysis>true</RunCodeAnalysis>
23 </PropertyGroup>
24 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
25 <DebugType>full</DebugType>
26 <Optimize>true</Optimize>
27 <OutputPath>bin\Release</OutputPath>
28 <DefineConstants>NET_4_5</DefineConstants>
29 <ErrorReport>prompt</ErrorReport>
30 <WarningLevel>4</WarningLevel>
31 <ConsolePause>false</ConsolePause>
32 </PropertyGroup>
33 <PropertyGroup>
34 <SignAssembly>false</SignAssembly>
35 </PropertyGroup>
36 <PropertyGroup>
37 <AssemblyOriginatorKeyFile>implab.snk</AssemblyOriginatorKeyFile>
38 </PropertyGroup>
39 <ItemGroup>
40 <Reference Include="System" />
41 <Reference Include="System.Xml" />
42 <Reference Include="mscorlib" />
43 <Reference Include="System.Xml.Linq" />
44 </ItemGroup>
45 <ItemGroup>
46 <Compile Include="Components\StateChangeEventArgs.cs" />
47 <Compile Include="CustomEqualityComparer.cs" />
48 <Compile Include="Diagnostics\ConsoleTraceListener.cs" />
49 <Compile Include="Diagnostics\LogChannel.cs" />
50 <Compile Include="Diagnostics\LogicalOperation.cs" />
51 <Compile Include="Diagnostics\TextFileListener.cs" />
52 <Compile Include="Diagnostics\Trace.cs" />
53 <Compile Include="Diagnostics\TraceLog.cs" />
54 <Compile Include="Diagnostics\TraceEvent.cs" />
55 <Compile Include="Diagnostics\TraceEventType.cs" />
56 <Compile Include="Diagnostics\TraceSourceAttribute.cs" />
57 <Compile Include="Formats\CharMap.cs" />
58 <Compile Include="Formats\FastInpurScanner.cs" />
59 <Compile Include="Formats\InputScanner.cs" />
60 <Compile Include="Formats\Json\JsonStringScanner.cs" />
61 <Compile Include="Formats\Json\JsonTextScanner.cs" />
62 <Compile Include="ICancellable.cs" />
63 <Compile Include="IProgressHandler.cs" />
64 <Compile Include="IProgressNotifier.cs" />
65 <Compile Include="IPromiseT.cs" />
66 <Compile Include="IPromise.cs" />
67 <Compile Include="IServiceLocator.cs" />
68 <Compile Include="ITaskController.cs" />
69 <Compile Include="Parallels\DispatchPool.cs" />
70 <Compile Include="Parallels\ArrayTraits.cs" />
71 <Compile Include="Parallels\SimpleAsyncQueue.cs" />
72 <Compile Include="Parallels\WorkerPool.cs" />
73 <Compile Include="ProgressInitEventArgs.cs" />
74 <Compile Include="Properties\AssemblyInfo.cs" />
75 <Compile Include="Parallels\AsyncPool.cs" />
76 <Compile Include="Safe.cs" />
77 <Compile Include="SyncContextPromise.cs" />
78 <Compile Include="ValueEventArgs.cs" />
79 <Compile Include="PromiseExtensions.cs" />
80 <Compile Include="SyncContextPromiseT.cs" />
81 <Compile Include="Diagnostics\OperationContext.cs" />
82 <Compile Include="Diagnostics\TraceContext.cs" />
83 <Compile Include="Diagnostics\LogEventArgs.cs" />
84 <Compile Include="Diagnostics\LogEventArgsT.cs" />
85 <Compile Include="Diagnostics\Extensions.cs" />
86 <Compile Include="PromiseEventType.cs" />
87 <Compile Include="Parallels\AsyncQueue.cs" />
88 <Compile Include="PromiseT.cs" />
89 <Compile Include="IDeferred.cs" />
90 <Compile Include="IDeferredT.cs" />
91 <Compile Include="Promise.cs" />
92 <Compile Include="PromiseTransientException.cs" />
93 <Compile Include="Parallels\Signal.cs" />
94 <Compile Include="Parallels\SharedLock.cs" />
95 <Compile Include="Diagnostics\ILogWriter.cs" />
96 <Compile Include="Diagnostics\ListenerBase.cs" />
97 <Compile Include="Parallels\BlockingQueue.cs" />
98 <Compile Include="AbstractEvent.cs" />
99 <Compile Include="AbstractPromise.cs" />
100 <Compile Include="AbstractPromiseT.cs" />
101 <Compile Include="FuncTask.cs" />
102 <Compile Include="FuncTaskBase.cs" />
103 <Compile Include="FuncTaskT.cs" />
104 <Compile Include="ActionChainTaskBase.cs" />
105 <Compile Include="ActionChainTask.cs" />
106 <Compile Include="ActionChainTaskT.cs" />
107 <Compile Include="FuncChainTaskBase.cs" />
108 <Compile Include="FuncChainTask.cs" />
109 <Compile Include="FuncChainTaskT.cs" />
110 <Compile Include="ActionTaskBase.cs" />
111 <Compile Include="ActionTask.cs" />
112 <Compile Include="ActionTaskT.cs" />
113 <Compile Include="ICancellationToken.cs" />
114 <Compile Include="SuccessPromise.cs" />
115 <Compile Include="SuccessPromiseT.cs" />
116 <Compile Include="PromiseAwaiterT.cs" />
117 <Compile Include="PromiseAwaiter.cs" />
118 <Compile Include="Components\ComponentContainer.cs" />
119 <Compile Include="Components\Disposable.cs" />
120 <Compile Include="Components\DisposablePool.cs" />
121 <Compile Include="Components\ObjectPool.cs" />
122 <Compile Include="Components\ServiceLocator.cs" />
123 <Compile Include="Components\IInitializable.cs" />
124 <Compile Include="TaskController.cs" />
125 <Compile Include="Components\App.cs" />
126 <Compile Include="Components\IRunnable.cs" />
127 <Compile Include="Components\ExecutionState.cs" />
128 <Compile Include="Components\RunnableComponent.cs" />
129 <Compile Include="Components\IFactory.cs" />
130 <Compile Include="Automaton\IAlphabet.cs" />
131 <Compile Include="Automaton\ParserException.cs" />
132 <Compile Include="Automaton\IndexedAlphabetBase.cs" />
133 <Compile Include="Automaton\IAlphabetBuilder.cs" />
134 <Compile Include="Automaton\RegularExpressions\AltToken.cs" />
135 <Compile Include="Automaton\RegularExpressions\BinaryToken.cs" />
136 <Compile Include="Automaton\RegularExpressions\CatToken.cs" />
137 <Compile Include="Automaton\RegularExpressions\StarToken.cs" />
138 <Compile Include="Automaton\RegularExpressions\SymbolToken.cs" />
139 <Compile Include="Automaton\RegularExpressions\EmptyToken.cs" />
140 <Compile Include="Automaton\RegularExpressions\Token.cs" />
141 <Compile Include="Automaton\RegularExpressions\IVisitor.cs" />
142 <Compile Include="Automaton\AutomatonTransition.cs" />
143 <Compile Include="Formats\Json\JsonElementContext.cs" />
144 <Compile Include="Formats\Json\JsonElementType.cs" />
145 <Compile Include="Formats\Json\JsonGrammar.cs" />
146 <Compile Include="Formats\Json\JsonReader.cs" />
147 <Compile Include="Formats\Json\JsonScanner.cs" />
148 <Compile Include="Formats\Json\JsonTokenType.cs" />
149 <Compile Include="Formats\Json\JsonWriter.cs" />
150 <Compile Include="Formats\Json\StringTranslator.cs" />
151 <Compile Include="Automaton\MapAlphabet.cs" />
152 <Compile Include="Formats\CharAlphabet.cs" />
153 <Compile Include="Formats\ByteAlphabet.cs" />
154 <Compile Include="Automaton\IDFATable.cs" />
155 <Compile Include="Automaton\IDFATableBuilder.cs" />
156 <Compile Include="Automaton\DFATable.cs" />
157 <Compile Include="Automaton\RegularExpressions\RegularExpressionVisitor.cs" />
158 <Compile Include="Automaton\RegularExpressions\ITaggedDFABuilder.cs" />
159 <Compile Include="Formats\Grammar.cs" />
160 <Compile Include="Automaton\RegularExpressions\EndTokenT.cs" />
161 <Compile Include="Automaton\RegularExpressions\EndToken.cs" />
162 <Compile Include="Automaton\RegularExpressions\RegularExpressionVisitorT.cs" />
163 <Compile Include="Automaton\AutomatonConst.cs" />
164 <Compile Include="Automaton\RegularExpressions\RegularDFA.cs" />
165 <Compile Include="Components\LazyAndWeak.cs" />
166 <Compile Include="AbstractTask.cs" />
167 <Compile Include="AbstractTaskT.cs" />
168 <Compile Include="FailedPromise.cs" />
169 <Compile Include="FailedPromiseT.cs" />
170 <Compile Include="Components\PollingComponent.cs" />
171 <Compile Include="Xml\JsonXmlReader.cs" />
172 <Compile Include="Xml\JsonXmlReaderOptions.cs" />
173 <Compile Include="Xml\JsonXmlReaderPosition.cs" />
174 <Compile Include="Xml\SerializationHelpers.cs" />
175 <Compile Include="Xml\SerializersPool.cs" />
176 <Compile Include="Xml\XmlSimpleAttribute.cs" />
177 <Compile Include="Xml\XmlNameContext.cs" />
178 </ItemGroup>
179 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
180 <ItemGroup>
181 <None Include="Implab.nuspec">
182 <SubType>Designer</SubType>
183 </None>
184 <None Include="implab.snk" />
185 </ItemGroup>
186 <ItemGroup>
187 <Content Include="license.txt" />
188 </ItemGroup>
189 </Project> No newline at end of file
@@ -0,0 +1,54
1 {
2 "FormattingOptions": {
3 "NewLine": "\n",
4 "UseTabs": false,
5 "TabSize": 4,
6 "IndentationSize": 4,
7 "SpacingAfterMethodDeclarationName": false,
8 "SpaceWithinMethodDeclarationParenthesis": false,
9 "SpaceBetweenEmptyMethodDeclarationParentheses": false,
10 "SpaceAfterMethodCallName": false,
11 "SpaceWithinMethodCallParentheses": false,
12 "SpaceBetweenEmptyMethodCallParentheses": false,
13 "SpaceAfterControlFlowStatementKeyword": true,
14 "SpaceWithinExpressionParentheses": false,
15 "SpaceWithinCastParentheses": false,
16 "SpaceWithinOtherParentheses": false,
17 "SpaceAfterCast": false,
18 "SpacesIgnoreAroundVariableDeclaration": false,
19 "SpaceBeforeOpenSquareBracket": false,
20 "SpaceBetweenEmptySquareBrackets": false,
21 "SpaceWithinSquareBrackets": false,
22 "SpaceAfterColonInBaseTypeDeclaration": true,
23 "SpaceAfterComma": true,
24 "SpaceAfterDot": false,
25 "SpaceAfterSemicolonsInForStatement": true,
26 "SpaceBeforeColonInBaseTypeDeclaration": true,
27 "SpaceBeforeComma": false,
28 "SpaceBeforeDot": false,
29 "SpaceBeforeSemicolonsInForStatement": false,
30 "SpacingAroundBinaryOperator": "single",
31 "IndentBraces": false,
32 "IndentBlock": true,
33 "IndentSwitchSection": true,
34 "IndentSwitchCaseSection": true,
35 "LabelPositioning": "oneLess",
36 "WrappingPreserveSingleLine": true,
37 "WrappingKeepStatementsOnSingleLine": true,
38 "NewLinesForBracesInTypes": false,
39 "NewLinesForBracesInMethods": false,
40 "NewLinesForBracesInProperties": false,
41 "NewLinesForBracesInAccessors": false,
42 "NewLinesForBracesInAnonymousMethods": false,
43 "NewLinesForBracesInControlBlocks": false,
44 "NewLinesForBracesInAnonymousTypes": false,
45 "NewLinesForBracesInObjectCollectionArrayInitializers": false,
46 "NewLinesForBracesInLambdaExpressionBody": false,
47 "NewLineForElse": false,
48 "NewLineForCatch": false,
49 "NewLineForFinally": false,
50 "NewLineForMembersInObjectInit": false,
51 "NewLineForMembersInAnonymousTypes": false,
52 "NewLineForClausesInQuery": false
53 }
54 } No newline at end of file
@@ -1,300 +1,298
1 1 using System;
2 2 using Implab.Parallels;
3 3 using System.Threading;
4 4 using System.Reflection;
5 5
6 6 namespace Implab {
7 public abstract class AbstractEvent<THandler> : ICancellationToken, ICancellable {
7 public abstract class AbstractEvent<THandler> : ICancellable {
8 8
9 9 const int UNRESOLVED_SATE = 0;
10 10 const int TRANSITIONAL_STATE = 1;
11 11 protected const int SUCCEEDED_STATE = 2;
12 12 protected const int REJECTED_STATE = 3;
13 13 protected const int CANCELLED_STATE = 4;
14 14
15 15 const int CANCEL_NOT_REQUESTED = 0;
16 16 const int CANCEL_REQUESTING = 1;
17 17 const int CANCEL_REQUESTED = 2;
18 18
19 19 const int RESERVED_HANDLERS_COUNT = 4;
20 20
21 21 int m_state;
22 22 Exception m_error;
23 23 int m_handlersCount;
24 24
25 25 //readonly THandler[] m_handlers = new THandler[RESERVED_HANDLERS_COUNT];
26 26 THandler[] m_handlers;
27 27 SimpleAsyncQueue<THandler> m_extraHandlers;
28 28 int m_handlerPointer = -1;
29 29 int m_handlersCommited;
30 30
31 31 int m_cancelRequest;
32 32 Exception m_cancelationReason;
33 SimpleAsyncQueue<Action<Exception>> m_cancelationHandlers;
34
35 33
36 34 #region state managment
37 35 bool BeginTransit() {
38 36 return UNRESOLVED_SATE == Interlocked.CompareExchange(ref m_state, TRANSITIONAL_STATE, UNRESOLVED_SATE);
39 37 }
40 38
41 39 void CompleteTransit(int state) {
42 40 if (TRANSITIONAL_STATE != Interlocked.CompareExchange(ref m_state, state, TRANSITIONAL_STATE))
43 41 throw new InvalidOperationException("Can't complete transition when the object isn't in the transitional state");
44 42 }
45 43
46 44 void WaitTransition() {
47 45 while (m_state == TRANSITIONAL_STATE) {
48 46 Thread.MemoryBarrier();
49 47 }
50 48 }
51 49
52 50 protected bool BeginSetResult() {
53 51 if (!BeginTransit()) {
54 52 WaitTransition();
55 53 if (m_state != CANCELLED_STATE)
56 54 throw new InvalidOperationException("The promise is already resolved");
57 55 return false;
58 56 }
59 57 return true;
60 58 }
61 59
62 60 protected void EndSetResult() {
63 61 CompleteTransit(SUCCEEDED_STATE);
64 62 Signal();
65 63 }
66 64
67 65
68 66
69 67 /// <summary>
70 68 /// Выполняет обещание, сообщая об ошибке
71 69 /// </summary>
72 70 /// <remarks>
73 71 /// Поскольку обещание должно работать в многопточной среде, при его выполнении сразу несколько потоков
74 72 /// могу вернуть ошибку, при этом только первая будет использована в качестве результата, остальные
75 73 /// будут проигнорированы.
76 74 /// </remarks>
77 75 /// <param name="error">Исключение возникшее при выполнении операции</param>
78 76 /// <exception cref="InvalidOperationException">Данное обещание уже выполнено</exception>
79 77 protected void SetError(Exception error) {
80 78 if (BeginTransit()) {
81 79 m_error = error;
82 80 CompleteTransit(REJECTED_STATE);
83 81
84 82 Signal();
85 83 } else {
86 84 WaitTransition();
87 85 if (m_state == SUCCEEDED_STATE)
88 86 throw new InvalidOperationException("The promise is already resolved");
89 87 }
90 88 }
91 89
92 90 /// <summary>
93 91 /// Отменяет операцию, если это возможно.
94 92 /// </summary>
95 93 /// <remarks>Для определения была ли операция отменена следует использовать свойство <see cref="IsCancelled"/>.</remarks>
96 94 protected void SetCancelled(Exception reason) {
97 95 if (BeginTransit()) {
98 96 m_error = reason;
99 97 CompleteTransit(CANCELLED_STATE);
100 98 Signal();
101 99 }
102 100 }
103 101
104 102 protected abstract void SignalHandler(THandler handler, int signal);
105 103
106 104 void Signal() {
107 105 var hp = m_handlerPointer;
108 106 var slot = hp +1 ;
109 107 while (slot < m_handlersCommited) {
110 108 if (Interlocked.CompareExchange(ref m_handlerPointer, slot, hp) == hp) {
111 109 SignalHandler(m_handlers[slot], m_state);
112 110 }
113 111 hp = m_handlerPointer;
114 112 slot = hp +1 ;
115 113 }
116 114
117 115
118 116 if (m_extraHandlers != null) {
119 117 THandler handler;
120 118 while (m_extraHandlers.TryDequeue(out handler))
121 119 SignalHandler(handler, m_state);
122 120 }
123 121 }
124 122
125 123 #endregion
126 124
127 125 protected abstract Signal GetResolveSignal();
128 126
129 127 #region synchronization traits
130 128 protected void WaitResult(int timeout) {
131 129 if (!(IsResolved || GetResolveSignal().Wait(timeout)))
132 130 throw new TimeoutException();
133 131
134 132 switch (m_state) {
135 133 case SUCCEEDED_STATE:
136 134 return;
137 135 case CANCELLED_STATE:
138 136 throw new OperationCanceledException("The operation has been cancelled", m_error);
139 137 case REJECTED_STATE:
140 138 throw new TargetInvocationException(m_error);
141 139 default:
142 140 throw new ApplicationException(String.Format("The promise state {0} is invalid", m_state));
143 141 }
144 142 }
145 143 #endregion
146 144
147 145 #region handlers managment
148 146
149 147 protected void AddHandler(THandler handler) {
150 148
151 149 if (m_state > 1) {
152 150 // the promise is in the resolved state, just invoke the handler
153 151 SignalHandler(handler, m_state);
154 152 } else {
155 153 var slot = Interlocked.Increment(ref m_handlersCount) - 1;
156 154
157 155 if (slot < RESERVED_HANDLERS_COUNT) {
158 156
159 157 if (slot == 0) {
160 158 m_handlers = new THandler[RESERVED_HANDLERS_COUNT];
161 159 } else {
162 160 while (m_handlers == null)
163 161 Thread.MemoryBarrier();
164 162 }
165 163
166 164 m_handlers[slot] = handler;
167 165
168 166 while (slot != Interlocked.CompareExchange(ref m_handlersCommited, slot + 1, slot)) {
169 167 }
170 168
171 169 if (m_state > 1) {
172 170 do {
173 171 var hp = m_handlerPointer;
174 172 slot = hp + 1;
175 173 if (slot < m_handlersCommited) {
176 174 if (Interlocked.CompareExchange(ref m_handlerPointer, slot, hp) != hp)
177 175 continue;
178 176 SignalHandler(m_handlers[slot], m_state);
179 177 }
180 178 break;
181 179 } while(true);
182 180 }
183 181 } else {
184 182 if (slot == RESERVED_HANDLERS_COUNT) {
185 183 m_extraHandlers = new SimpleAsyncQueue<THandler>();
186 184 } else {
187 185 while (m_extraHandlers == null)
188 186 Thread.MemoryBarrier();
189 187 }
190 188
191 189 m_extraHandlers.Enqueue(handler);
192 190
193 191 if (m_state > 1 && m_extraHandlers.TryDequeue(out handler))
194 192 // if the promise have been resolved while we was adding the handler to the queue
195 193 // we can't guarantee that someone is still processing it
196 194 // therefore we need to fetch a handler from the queue and execute it
197 195 // note that fetched handler may be not the one that we have added
198 196 // even we can fetch no handlers at all :)
199 197 SignalHandler(handler, m_state);
200 198 }
201 199 }
202 200 }
203 201
204 202 #endregion
205 203
206 204 #region IPromise implementation
207 205
208 206 public bool IsResolved {
209 207 get {
210 208 Thread.MemoryBarrier();
211 209 return m_state > 1;
212 210 }
213 211 }
214 212
215 213 public bool IsCancelled {
216 214 get {
217 215 Thread.MemoryBarrier();
218 216 return m_state == CANCELLED_STATE;
219 217 }
220 218 }
221 219
222 220 #endregion
223 221
224 222 public Exception Error {
225 223 get {
226 224 return m_error;
227 225 }
228 226 }
229 227
230 228 public bool CancelOperationIfRequested() {
231 229 if (IsCancellationRequested) {
232 230 CancelOperation(CancellationReason);
233 231 return true;
234 232 }
235 233 return false;
236 234 }
237 235
238 236 public virtual void CancelOperation(Exception reason) {
239 237 SetCancelled(reason);
240 238 }
241 239
242 240 public void CancellationRequested(Action<Exception> handler) {
243 241 Safe.ArgumentNotNull(handler, "handler");
244 242 if (IsCancellationRequested)
245 243 handler(CancellationReason);
246 244
247 245 if (m_cancelationHandlers == null)
248 246 Interlocked.CompareExchange(ref m_cancelationHandlers, new SimpleAsyncQueue<Action<Exception>>(), null);
249 247
250 248 m_cancelationHandlers.Enqueue(handler);
251 249
252 250 if (IsCancellationRequested && m_cancelationHandlers.TryDequeue(out handler))
253 251 // TryDeque implies MemoryBarrier()
254 252 handler(m_cancelationReason);
255 253 }
256 254
257 255 public bool IsCancellationRequested {
258 256 get {
259 257 do {
260 258 if (m_cancelRequest == CANCEL_NOT_REQUESTED)
261 259 return false;
262 260 if (m_cancelRequest == CANCEL_REQUESTED)
263 261 return true;
264 262 Thread.MemoryBarrier();
265 263 } while(true);
266 264 }
267 265 }
268 266
269 267 public Exception CancellationReason {
270 268 get {
271 269 do {
272 270 Thread.MemoryBarrier();
273 271 } while(m_cancelRequest == CANCEL_REQUESTING);
274 272
275 273 return m_cancelationReason;
276 274 }
277 275 }
278 276
279 277 #region ICancellable implementation
280 278
281 279 public void Cancel() {
282 280 Cancel(null);
283 281 }
284 282
285 283 public void Cancel(Exception reason) {
286 284 if (CANCEL_NOT_REQUESTED == Interlocked.CompareExchange(ref m_cancelRequest, CANCEL_REQUESTING, CANCEL_NOT_REQUESTED)) {
287 285 m_cancelationReason = reason;
288 286 m_cancelRequest = CANCEL_REQUESTED;
289 287 if (m_cancelationHandlers != null) {
290 288 Action<Exception> handler;
291 289 while (m_cancelationHandlers.TryDequeue(out handler))
292 290 handler(m_cancelationReason);
293 291 }
294 292 }
295 293 }
296 294
297 295 #endregion
298 296 }
299 297 }
300 298
@@ -1,348 +1,348
1 1 using Implab;
2 2 using System;
3 3 using System.Collections.Generic;
4 4 using System.Linq;
5 5 using System.Diagnostics;
6 6 using System.IO;
7 7 using System.CodeDom.Compiler;
8 8 using System.CodeDom;
9 9
10 10 namespace Implab.Automaton {
11 11 public class DFATable : IDFATableBuilder {
12 12 int m_stateCount;
13 13 int m_symbolCount;
14 14 int m_initialState;
15 15
16 16 readonly HashSet<int> m_finalStates = new HashSet<int>();
17 17 readonly HashSet<AutomatonTransition> m_transitions = new HashSet<AutomatonTransition>();
18 18
19 19
20 20 #region IDFADefinition implementation
21 21
22 22 public bool IsFinalState(int s) {
23 23 Safe.ArgumentInRange(s, 0, m_stateCount, "s");
24 24
25 25 return m_finalStates.Contains(s);
26 26 }
27 27
28 28 public IEnumerable<int> FinalStates {
29 29 get {
30 30 return m_finalStates;
31 31 }
32 32 }
33 33
34 34 public int StateCount {
35 35 get { return m_stateCount; }
36 36 }
37 37
38 38 public int AlphabetSize {
39 39 get { return m_symbolCount; }
40 40 }
41 41
42 42 public int InitialState {
43 43 get { return m_initialState; }
44 44 }
45 45
46 46 #endregion
47 47
48 48 public void SetInitialState(int s) {
49 49 Safe.ArgumentAssert(s >= 0, "s");
50 50 m_stateCount = Math.Max(m_stateCount, s + 1);
51 51 m_initialState = s;
52 52 }
53 53
54 54 public void MarkFinalState(int state) {
55 55 m_stateCount = Math.Max(m_stateCount, state + 1);
56 56 m_finalStates.Add(state);
57 57 }
58 58
59 59 public void Add(AutomatonTransition item) {
60 60 Safe.ArgumentAssert(item.s1 >= 0, "item");
61 61 Safe.ArgumentAssert(item.s2 >= 0, "item");
62 62 Safe.ArgumentAssert(item.edge >= 0, "item");
63 63
64 64 m_stateCount = Math.Max(m_stateCount, Math.Max(item.s1, item.s2) + 1);
65 65 m_symbolCount = Math.Max(m_symbolCount, item.edge + 1);
66 66
67 67 m_transitions.Add(item);
68 68 }
69 69
70 70 public void Clear() {
71 71 m_stateCount = 0;
72 72 m_symbolCount = 0;
73 73 m_finalStates.Clear();
74 74 m_transitions.Clear();
75 75 }
76 76
77 77 public bool Contains(AutomatonTransition item) {
78 78 return m_transitions.Contains(item);
79 79 }
80 80
81 81 public void CopyTo(AutomatonTransition[] array, int arrayIndex) {
82 82 m_transitions.CopyTo(array, arrayIndex);
83 83 }
84 84
85 85 public bool Remove(AutomatonTransition item) {
86 86 return m_transitions.Remove(item);
87 87 }
88 88
89 89 public int Count {
90 90 get {
91 91 return m_transitions.Count;
92 92 }
93 93 }
94 94
95 95 public bool IsReadOnly {
96 96 get {
97 97 return false;
98 98 }
99 99 }
100 100
101 101 public IEnumerator<AutomatonTransition> GetEnumerator() {
102 102 return m_transitions.GetEnumerator();
103 103 }
104 104
105 105 System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
106 106 return GetEnumerator();
107 107 }
108 108
109 109 public void AddSymbol(int symbol) {
110 110 Safe.ArgumentAssert(symbol >= 0, "symbol");
111 111 m_symbolCount = Math.Max(symbol + 1, m_symbolCount);
112 112 }
113 113
114 114 public int[,] CreateTransitionTable() {
115 115 var table = new int[StateCount,AlphabetSize];
116 116
117 117 for (int i = 0; i < StateCount; i++)
118 118 for (int j = 0; j < AlphabetSize; j++)
119 119 table[i, j] = AutomatonConst.UnreachableState;
120 120
121 121 foreach (var t in this)
122 122 table[t.s1,t.edge] = (byte)t.s2;
123 123
124 124 return table;
125 125 }
126 126
127 127 public bool[] CreateFinalStateTable() {
128 128 var table = new bool[StateCount];
129 129
130 130 foreach (var s in FinalStates)
131 131 table[s] = true;
132 132
133 133 return table;
134 134 }
135 135
136 136 /// <summary>Формирует множества конечных состояний перед началом работы алгоритма минимизации.</summary>
137 137 /// <remarks>
138 138 /// В процессе построения минимального автомата требуется разделить множество состояний,
139 139 /// на два подмножества - конечные состояния и все остальные, после чего эти подмножества
140 140 /// будут резделены на более мелкие. Иногда требуется гарантировать различия конечных сосотяний,
141 141 /// для этого необходимо переопределить даннцю фукнцию, для получения множеств конечных состояний.
142 142 /// </remarks>
143 143 /// <returns>The final states.</returns>
144 144 protected virtual IEnumerable<HashSet<int>> SplitFinalStates(IEnumerable<int> states) {
145 145 return new [] { new HashSet<int>(states) };
146 146 }
147 147
148 148 protected void Optimize(
149 149 IDFATableBuilder optimalDFA,
150 150 IDictionary<int,int> alphabetMap,
151 151 IDictionary<int,int> stateMap
152 152 ) {
153 153 Safe.ArgumentNotNull(optimalDFA, "dfa");
154 154 Safe.ArgumentNotNull(alphabetMap, "alphabetMap");
155 155 Safe.ArgumentNotNull(stateMap, "stateMap");
156 156
157 157
158 158 var setComparer = new CustomEqualityComparer<HashSet<int>>(
159 159 (x, y) => x.SetEquals(y),
160 160 s => s.Sum(x => x.GetHashCode())
161 161 );
162 162
163 163 var optimalStates = new HashSet<HashSet<int>>(setComparer);
164 164 var queue = new HashSet<HashSet<int>>(setComparer);
165 165
166 166 optimalStates.Add(new HashSet<int>(FinalStates));
167 167
168 168 var state = new HashSet<int>(
169 169 Enumerable
170 170 .Range(0, m_stateCount)
171 171 .Where(i => !m_finalStates.Contains(i))
172 172 );
173 173
174 174 optimalStates.Add(state);
175 175 queue.Add(state);
176 176
177 177 var rmap = m_transitions
178 178 .GroupBy(t => t.s2)
179 179 .ToDictionary(
180 180 g => g.Key, // s2
181 181 g => g.ToLookup(t => t.edge, t => t.s1)//.ToDictionary(p => p.Key)
182 182 );
183 183
184 184 while (queue.Count > 0) {
185 185 var stateA = queue.First();
186 186 queue.Remove(stateA);
187 187
188 188 for (int c = 0; c < m_symbolCount; c++) {
189 189 var stateX = new HashSet<int>();
190 190 foreach(var a in stateA.Where(rmap.ContainsKey))
191 191 stateX.UnionWith(rmap[a][c]); // all states from wich the symbol 'c' leads to the state 'a'
192 192
193 193 var tmp = optimalStates.ToArray();
194 194 foreach (var stateY in tmp) {
195 195 var stateR1 = new HashSet<int>(stateY);
196 196 var stateR2 = new HashSet<int>(stateY);
197 197
198 198 stateR1.IntersectWith(stateX);
199 199 stateR2.ExceptWith(stateX);
200 200
201 201 if (stateR1.Count > 0 && stateR2.Count > 0) {
202 202
203 203
204 204 optimalStates.Remove(stateY);
205 205 optimalStates.Add(stateR1);
206 206 optimalStates.Add(stateR2);
207 207
208 208 if (queue.Contains(stateY)) {
209 209 queue.Remove(stateY);
210 210 queue.Add(stateR1);
211 211 queue.Add(stateR2);
212 212 } else {
213 213 queue.Add(stateR1.Count <= stateR2.Count ? stateR1 : stateR2);
214 214 }
215 215 }
216 216 }
217 217 }
218 218 }
219 219
220 220 // дополнительно разбиваем конечные состояния
221 221 foreach (var final in optimalStates.Where(s => s.Overlaps(m_finalStates)).ToArray()) {
222 222 optimalStates.Remove(final);
223 223 foreach (var split in SplitFinalStates(final))
224 224 optimalStates.Add(split);
225 225 }
226 226
227 227
228 228 // карта получения оптимального состояния по соотвествующему ему простому состоянию
229 229 var nextState = 0;
230 230 foreach (var item in optimalStates) {
231 231 var id = nextState++;
232 232 foreach (var s in item)
233 233 stateMap[s] = id;
234 234 }
235 235
236 236 // получаем минимальный алфавит
237 237 // входные символы не различимы, если Move(s,a1) == Move(s,a2), для любого s
238 238 // для этого используем алгоритм кластеризации, сначала
239 239 // считаем, что все символы не различимы
240 240
241 241 var minClasses = new HashSet<HashSet<int>>(setComparer);
242 242 var alphaQueue = new Queue<HashSet<int>>();
243 243 alphaQueue.Enqueue(new HashSet<int>(Enumerable.Range(0,AlphabetSize)));
244 244
245 245 // для всех состояний, будем проверять каждый класс на различимость,
246 246 // т.е. символы различимы, если они приводят к разным состояниям
247 247 for (int s = 0 ; s < optimalStates.Count; s++) {
248 248 var newQueue = new Queue<HashSet<int>>();
249 249
250 250 foreach (var A in alphaQueue) {
251 251 // классы из одного символа делить бесполезно, переводим их сразу в
252 252 // результирующий алфавит
253 253 if (A.Count == 1) {
254 254 minClasses.Add(A);
255 255 continue;
256 256 }
257 257
258 258 // различаем классы символов, которые переводят в различные оптимальные состояния
259 259 // optimalState -> alphaClass
260 260 var classes = new Dictionary<int, HashSet<int>>();
261 261
262 262 foreach (var term in A) {
263 263 // ищем все переходы класса по символу term
264 264 var s2 = m_transitions.Where(t => stateMap[t.s1] == s && t.edge == term).Select(t => stateMap[t.s2]).DefaultIfEmpty(-1).First();
265 265
266 266 HashSet<int> a2;
267 267 if (!classes.TryGetValue(s2, out a2)) {
268 268 a2 = new HashSet<int>();
269 269 newQueue.Enqueue(a2);
270 270 classes[s2] = a2;
271 271 }
272 272 a2.Add(term);
273 273 }
274 274 }
275 275
276 276 if (newQueue.Count == 0)
277 277 break;
278 278 alphaQueue = newQueue;
279 279 }
280 280
281 281 // после окончания работы алгоритма в очереди останутся минимальные различимые классы
282 282 // входных символов
283 283 foreach (var A in alphaQueue)
284 284 minClasses.Add(A);
285 285
286 286 // построение отображения алфавитов входных символов.
287 287 // поскольку символ DFAConst.UNCLASSIFIED_INPUT может иметь
288 288 // специальное значение, тогда сохраним минимальный класс,
289 289 // содержащий этот символ на томже месте.
290 290
291 291 var nextCls = 0;
292 292 foreach (var item in minClasses) {
293 293 if (nextCls == AutomatonConst.UnclassifiedInput)
294 294 nextCls++;
295 295
296 296 // сохраняем DFAConst.UNCLASSIFIED_INPUT
297 297 var cls = item.Contains(AutomatonConst.UnclassifiedInput) ? AutomatonConst.UnclassifiedInput : nextCls++;
298 298 optimalDFA.AddSymbol(cls);
299 299
300 300 foreach (var a in item)
301 301 alphabetMap[a] = cls;
302 302 }
303 303
304 304 // построение автомата
305 305 optimalDFA.SetInitialState(stateMap[m_initialState]);
306 306
307 307 foreach (var sf in m_finalStates.Select(s => stateMap[s]).Distinct())
308 308 optimalDFA.MarkFinalState(sf);
309 309
310 310 foreach (var t in m_transitions.Select(t => new AutomatonTransition(stateMap[t.s1],stateMap[t.s2],alphabetMap[t.edge])).Distinct())
311 311 optimalDFA.Add(t);
312 312 }
313 313
314 protected string PrintDFA<TInput, TState>(IAlphabet<TInput> inputAlphabet, IAlphabet<TState> stateAlphabet) {
314 /*protected string PrintDFA<TInput, TState>(IAlphabet<TInput> inputAlphabet, IAlphabet<TState> stateAlphabet) {
315 315 Safe.ArgumentNotNull(inputAlphabet, "inputAlphabet");
316 316 Safe.ArgumentNotNull(stateAlphabet, "stateAlphabet");
317 317
318 318 var data = new List<string>();
319 319
320 320 data.Add("digraph dfa {");
321 321
322 322 foreach (var final in m_finalStates)
323 323 data.Add(String.Format("{0} [shape=box];",String.Join("", stateAlphabet.GetSymbols(final))));
324 324
325 325 foreach (var t in m_transitions)
326 326 data.Add(String.Format(
327 327 "{0} -> {2} [label={1}];",
328 328 String.Join("", stateAlphabet.GetSymbols(t.s1)),
329 329 ToLiteral(ToLiteral(String.Join("", t.edge == AutomatonConst.UnclassifiedInput ? new [] { "@" } : inputAlphabet.GetSymbols(t.edge).Select(x => x.ToString())))),
330 330 String.Join("", stateAlphabet.GetSymbols(t.s2))
331 331 ));
332 332 data.Add("}");
333 333 return String.Join("\n", data);
334 334 }
335 335
336 336 static string ToLiteral(string input)
337 337 {
338 338 using (var writer = new StringWriter())
339 339 {
340 340 using (var provider = CodeDomProvider.CreateProvider("CSharp"))
341 341 {
342 342 provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
343 343 return writer.ToString();
344 344 }
345 345 }
346 }
346 }*/
347 347 }
348 348 }
@@ -1,91 +1,91
1 1 using System.Collections.Generic;
2 2 using System.Linq;
3 3
4 4 namespace Implab.Automaton.RegularExpressions {
5 5 public class RegularDFA<TInput, TTag> : DFATable, ITaggedDFABuilder<TTag> {
6 6
7 7 readonly Dictionary<int,TTag[]> m_tags = new Dictionary<int, TTag[]>();
8 8 readonly IAlphabet<TInput> m_alphabet;
9 9
10 10 public RegularDFA(IAlphabet<TInput> alphabet) {
11 11 Safe.ArgumentNotNull(alphabet, "aplhabet");
12 12
13 13 m_alphabet = alphabet;
14 14 }
15 15
16 16
17 17 public IAlphabet<TInput> InputAlphabet {
18 18 get {
19 19 return m_alphabet;
20 20 }
21 21 }
22 22
23 23 public void MarkFinalState(int s, TTag[] tags) {
24 24 MarkFinalState(s);
25 25 SetStateTag(s, tags);
26 26 }
27 27
28 28 public void SetStateTag(int s, TTag[] tags) {
29 29 Safe.ArgumentNotNull(tags, "tags");
30 30 m_tags[s] = tags;
31 31 }
32 32
33 33 public TTag[] GetStateTag(int s) {
34 34 TTag[] tags;
35 35 return m_tags.TryGetValue(s, out tags) ? tags : new TTag[0];
36 36 }
37 37
38 38 public TTag[][] CreateTagTable() {
39 39 var table = new TTag[StateCount][];
40 40
41 41 foreach (var pair in m_tags)
42 42 table[pair.Key] = pair.Value;
43 43
44 44 return table;
45 45 }
46 46
47 47 /// <summary>
48 48 /// Optimize the specified alphabet.
49 49 /// </summary>
50 50 /// <param name="alphabet">Пустой алфавит, который будет зполнен в процессе оптимизации.</param>
51 51 public RegularDFA<TInput,TTag> Optimize(IAlphabetBuilder<TInput> alphabet) {
52 52 Safe.ArgumentNotNull(alphabet, "alphabet");
53 53
54 54 var dfa = new RegularDFA<TInput, TTag>(alphabet);
55 55
56 56 var alphaMap = new Dictionary<int,int>();
57 57 var stateMap = new Dictionary<int,int>();
58 58
59 59 Optimize(dfa, alphaMap, stateMap);
60 60
61 61 // mark tags in the new DFA
62 62 foreach (var g in m_tags.Where(x => x.Key < StateCount).GroupBy(x => stateMap[x.Key], x => x.Value ))
63 63 dfa.SetStateTag(g.Key, g.SelectMany(x => x).ToArray());
64 64
65 65 // make the alphabet for the new DFA
66 66 // skip all unclassified symbols
67 67 foreach (var pair in alphaMap.Where(x => x.Value != 0))
68 68 alphabet.DefineClass(m_alphabet.GetSymbols(pair.Key), pair.Value);
69 69 return dfa;
70 70 }
71 71
72 72 protected override IEnumerable<HashSet<int>> SplitFinalStates(IEnumerable<int> states) {
73 73 var arrayComparer = new CustomEqualityComparer<TTag[]>(
74 74 (x,y) => x.Length == y.Length && x.All(it => y.Contains(it)),
75 75 x => x.Sum(it => x.GetHashCode())
76 76 );
77 77 return states.GroupBy(x => m_tags[x] ?? new TTag[0], arrayComparer).Select(g => new HashSet<int>(g));
78 78 }
79 79
80 public override string ToString() {
80 /*public override string ToString() {
81 81 var states = new MapAlphabet<string>(false, null);
82 82
83 83 for (int i = 0; i < StateCount; i++)
84 84 states.DefineSymbol(string.Format("s{0}", i), i);
85 85
86 86 return string.Format("//[RegularDFA {1} x {2}]\n{0}", PrintDFA(InputAlphabet, states),StateCount, AlphabetSize);
87 }
87 }*/
88 88
89 89 }
90 90 }
91 91
@@ -1,24 +1,31
1 1 using System;
2 2
3 3 namespace Implab {
4 4 /// <summary>
5 5 /// Deferred result, usually used by asynchronous services as the service part of the promise.
6 6 /// </summary>
7 public interface IDeferred : ICancellationToken {
7 public interface IDeferred {
8 8
9 9 void Resolve();
10 10
11 11 /// <summary>
12 12 /// Reject the promise with the specified error.
13 13 /// </summary>
14 14 /// <param name="error">The reason why the promise is rejected.</param>
15 15 /// <remarks>
16 16 /// Some exceptions are treated in a special case:
17 17 /// <see cref="OperationCanceledException"/> is interpreted as call to <see cref="Cancel()"/> method,
18 18 /// and <see cref="PromiseTransientException"/> is always unwrapped and its
19 19 /// <see cref="PromiseTransientException.InnerException"> is used as the reason to reject promise.
20 20 /// </remarks>
21 21 void Reject(Exception error);
22
23 /// <summary>
24 /// Marks current instance as cencelled with the specified reason.
25 /// </summary>
26 /// <param name="reason">The reason for the operation cancellation,
27 /// if not specified the new <see cref="OperationCanceledException"> will be created</param>
28 void SetCancelled(Exception reason);
22 29 }
23 30 }
24 31
@@ -1,10 +1,12
1 1 using System;
2 2
3 3 namespace Implab {
4 public interface IDeferred<in T> : ICancellationToken {
4 public interface IDeferred<in T> {
5 5 void Resolve(T value);
6 6
7 7 void Reject(Exception error);
8
9 void SetCancelled(Exception error);
8 10 }
9 11 }
10 12
@@ -1,189 +1,8
1 <?xml version="1.0" encoding="utf-8"?>
2 <Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
1 <Project Sdk="Microsoft.NET.Sdk">
2
3 3 <PropertyGroup>
4 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
5 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
6 <ProjectGuid>{F550F1F8-8746-4AD0-9614-855F4C4B7F05}</ProjectGuid>
7 <OutputType>Library</OutputType>
8 <RootNamespace>Implab</RootNamespace>
9 <AssemblyName>Implab</AssemblyName>
10 <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
11 <TargetFrameworkProfile />
12 </PropertyGroup>
13 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
14 <DebugSymbols>true</DebugSymbols>
15 <DebugType>full</DebugType>
16 <Optimize>true</Optimize>
17 <OutputPath>bin\Debug</OutputPath>
18 <DefineConstants>TRACE;DEBUG;NET_4_5</DefineConstants>
19 <ErrorReport>prompt</ErrorReport>
20 <WarningLevel>4</WarningLevel>
21 <ConsolePause>false</ConsolePause>
22 <RunCodeAnalysis>true</RunCodeAnalysis>
23 </PropertyGroup>
24 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
25 <DebugType>full</DebugType>
26 <Optimize>true</Optimize>
27 <OutputPath>bin\Release</OutputPath>
28 <DefineConstants>NET_4_5</DefineConstants>
29 <ErrorReport>prompt</ErrorReport>
30 <WarningLevel>4</WarningLevel>
31 <ConsolePause>false</ConsolePause>
32 </PropertyGroup>
33 <PropertyGroup>
34 <SignAssembly>false</SignAssembly>
35 </PropertyGroup>
36 <PropertyGroup>
37 <AssemblyOriginatorKeyFile>implab.snk</AssemblyOriginatorKeyFile>
4 <TargetFrameworks>netstandard2.0;net45</TargetFrameworks>
5 <FrameworkPathOverride Condition="'$(TargetFramework)'=='net45' and '$(OSTYPE)'=='linux'">/usr/lib/mono/4.5/</FrameworkPathOverride>
38 6 </PropertyGroup>
39 <ItemGroup>
40 <Reference Include="System" />
41 <Reference Include="System.Xml" />
42 <Reference Include="mscorlib" />
43 <Reference Include="System.Xml.Linq" />
44 </ItemGroup>
45 <ItemGroup>
46 <Compile Include="Components\StateChangeEventArgs.cs" />
47 <Compile Include="CustomEqualityComparer.cs" />
48 <Compile Include="Diagnostics\ConsoleTraceListener.cs" />
49 <Compile Include="Diagnostics\LogChannel.cs" />
50 <Compile Include="Diagnostics\LogicalOperation.cs" />
51 <Compile Include="Diagnostics\TextFileListener.cs" />
52 <Compile Include="Diagnostics\Trace.cs" />
53 <Compile Include="Diagnostics\TraceLog.cs" />
54 <Compile Include="Diagnostics\TraceEvent.cs" />
55 <Compile Include="Diagnostics\TraceEventType.cs" />
56 <Compile Include="Diagnostics\TraceSourceAttribute.cs" />
57 <Compile Include="Formats\CharMap.cs" />
58 <Compile Include="Formats\FastInpurScanner.cs" />
59 <Compile Include="Formats\InputScanner.cs" />
60 <Compile Include="Formats\Json\JsonStringScanner.cs" />
61 <Compile Include="Formats\Json\JsonTextScanner.cs" />
62 <Compile Include="ICancellable.cs" />
63 <Compile Include="IProgressHandler.cs" />
64 <Compile Include="IProgressNotifier.cs" />
65 <Compile Include="IPromiseT.cs" />
66 <Compile Include="IPromise.cs" />
67 <Compile Include="IServiceLocator.cs" />
68 <Compile Include="ITaskController.cs" />
69 <Compile Include="Parallels\DispatchPool.cs" />
70 <Compile Include="Parallels\ArrayTraits.cs" />
71 <Compile Include="Parallels\SimpleAsyncQueue.cs" />
72 <Compile Include="Parallels\WorkerPool.cs" />
73 <Compile Include="ProgressInitEventArgs.cs" />
74 <Compile Include="Properties\AssemblyInfo.cs" />
75 <Compile Include="Parallels\AsyncPool.cs" />
76 <Compile Include="Safe.cs" />
77 <Compile Include="SyncContextPromise.cs" />
78 <Compile Include="ValueEventArgs.cs" />
79 <Compile Include="PromiseExtensions.cs" />
80 <Compile Include="SyncContextPromiseT.cs" />
81 <Compile Include="Diagnostics\OperationContext.cs" />
82 <Compile Include="Diagnostics\TraceContext.cs" />
83 <Compile Include="Diagnostics\LogEventArgs.cs" />
84 <Compile Include="Diagnostics\LogEventArgsT.cs" />
85 <Compile Include="Diagnostics\Extensions.cs" />
86 <Compile Include="PromiseEventType.cs" />
87 <Compile Include="Parallels\AsyncQueue.cs" />
88 <Compile Include="PromiseT.cs" />
89 <Compile Include="IDeferred.cs" />
90 <Compile Include="IDeferredT.cs" />
91 <Compile Include="Promise.cs" />
92 <Compile Include="PromiseTransientException.cs" />
93 <Compile Include="Parallels\Signal.cs" />
94 <Compile Include="Parallels\SharedLock.cs" />
95 <Compile Include="Diagnostics\ILogWriter.cs" />
96 <Compile Include="Diagnostics\ListenerBase.cs" />
97 <Compile Include="Parallels\BlockingQueue.cs" />
98 <Compile Include="AbstractEvent.cs" />
99 <Compile Include="AbstractPromise.cs" />
100 <Compile Include="AbstractPromiseT.cs" />
101 <Compile Include="FuncTask.cs" />
102 <Compile Include="FuncTaskBase.cs" />
103 <Compile Include="FuncTaskT.cs" />
104 <Compile Include="ActionChainTaskBase.cs" />
105 <Compile Include="ActionChainTask.cs" />
106 <Compile Include="ActionChainTaskT.cs" />
107 <Compile Include="FuncChainTaskBase.cs" />
108 <Compile Include="FuncChainTask.cs" />
109 <Compile Include="FuncChainTaskT.cs" />
110 <Compile Include="ActionTaskBase.cs" />
111 <Compile Include="ActionTask.cs" />
112 <Compile Include="ActionTaskT.cs" />
113 <Compile Include="ICancellationToken.cs" />
114 <Compile Include="SuccessPromise.cs" />
115 <Compile Include="SuccessPromiseT.cs" />
116 <Compile Include="PromiseAwaiterT.cs" />
117 <Compile Include="PromiseAwaiter.cs" />
118 <Compile Include="Components\ComponentContainer.cs" />
119 <Compile Include="Components\Disposable.cs" />
120 <Compile Include="Components\DisposablePool.cs" />
121 <Compile Include="Components\ObjectPool.cs" />
122 <Compile Include="Components\ServiceLocator.cs" />
123 <Compile Include="Components\IInitializable.cs" />
124 <Compile Include="TaskController.cs" />
125 <Compile Include="Components\App.cs" />
126 <Compile Include="Components\IRunnable.cs" />
127 <Compile Include="Components\ExecutionState.cs" />
128 <Compile Include="Components\RunnableComponent.cs" />
129 <Compile Include="Components\IFactory.cs" />
130 <Compile Include="Automaton\IAlphabet.cs" />
131 <Compile Include="Automaton\ParserException.cs" />
132 <Compile Include="Automaton\IndexedAlphabetBase.cs" />
133 <Compile Include="Automaton\IAlphabetBuilder.cs" />
134 <Compile Include="Automaton\RegularExpressions\AltToken.cs" />
135 <Compile Include="Automaton\RegularExpressions\BinaryToken.cs" />
136 <Compile Include="Automaton\RegularExpressions\CatToken.cs" />
137 <Compile Include="Automaton\RegularExpressions\StarToken.cs" />
138 <Compile Include="Automaton\RegularExpressions\SymbolToken.cs" />
139 <Compile Include="Automaton\RegularExpressions\EmptyToken.cs" />
140 <Compile Include="Automaton\RegularExpressions\Token.cs" />
141 <Compile Include="Automaton\RegularExpressions\IVisitor.cs" />
142 <Compile Include="Automaton\AutomatonTransition.cs" />
143 <Compile Include="Formats\Json\JsonElementContext.cs" />
144 <Compile Include="Formats\Json\JsonElementType.cs" />
145 <Compile Include="Formats\Json\JsonGrammar.cs" />
146 <Compile Include="Formats\Json\JsonReader.cs" />
147 <Compile Include="Formats\Json\JsonScanner.cs" />
148 <Compile Include="Formats\Json\JsonTokenType.cs" />
149 <Compile Include="Formats\Json\JsonWriter.cs" />
150 <Compile Include="Formats\Json\StringTranslator.cs" />
151 <Compile Include="Automaton\MapAlphabet.cs" />
152 <Compile Include="Formats\CharAlphabet.cs" />
153 <Compile Include="Formats\ByteAlphabet.cs" />
154 <Compile Include="Automaton\IDFATable.cs" />
155 <Compile Include="Automaton\IDFATableBuilder.cs" />
156 <Compile Include="Automaton\DFATable.cs" />
157 <Compile Include="Automaton\RegularExpressions\RegularExpressionVisitor.cs" />
158 <Compile Include="Automaton\RegularExpressions\ITaggedDFABuilder.cs" />
159 <Compile Include="Formats\Grammar.cs" />
160 <Compile Include="Automaton\RegularExpressions\EndTokenT.cs" />
161 <Compile Include="Automaton\RegularExpressions\EndToken.cs" />
162 <Compile Include="Automaton\RegularExpressions\RegularExpressionVisitorT.cs" />
163 <Compile Include="Automaton\AutomatonConst.cs" />
164 <Compile Include="Automaton\RegularExpressions\RegularDFA.cs" />
165 <Compile Include="Components\LazyAndWeak.cs" />
166 <Compile Include="AbstractTask.cs" />
167 <Compile Include="AbstractTaskT.cs" />
168 <Compile Include="FailedPromise.cs" />
169 <Compile Include="FailedPromiseT.cs" />
170 <Compile Include="Components\PollingComponent.cs" />
171 <Compile Include="Xml\JsonXmlReader.cs" />
172 <Compile Include="Xml\JsonXmlReaderOptions.cs" />
173 <Compile Include="Xml\JsonXmlReaderPosition.cs" />
174 <Compile Include="Xml\SerializationHelpers.cs" />
175 <Compile Include="Xml\SerializersPool.cs" />
176 <Compile Include="Xml\XmlSimpleAttribute.cs" />
177 <Compile Include="Xml\XmlNameContext.cs" />
178 </ItemGroup>
179 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
180 <ItemGroup>
181 <None Include="Implab.nuspec">
182 <SubType>Designer</SubType>
183 </None>
184 <None Include="implab.snk" />
185 </ItemGroup>
186 <ItemGroup>
187 <Content Include="license.txt" />
188 </ItemGroup>
189 </Project> No newline at end of file
7
8 </Project>
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed, binary diff hidden
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
General Comments 3
Under Review
author

Auto status change to "Under Review"

Approved
author

ok, latest stable version should be in default

You need to be logged in to leave comments. Login now