├── .gitignore
├── LazyTask.Test
├── LazyTask.Test.csproj
└── Tests.cs
├── LazyTask.sln
├── LazyTask
├── LazyTask.cs
├── LazyTask.csproj
└── LazyTaskMethodBuilder.cs
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 | [Ll]ogs/
33 |
34 | # Visual Studio 2015/2017 cache/options directory
35 | .vs/
36 | # Uncomment if you have tasks that create the project's static files in wwwroot
37 | #wwwroot/
38 |
39 | # Visual Studio 2017 auto generated files
40 | Generated\ Files/
41 |
42 | # MSTest test Results
43 | [Tt]est[Rr]esult*/
44 | [Bb]uild[Ll]og.*
45 |
46 | # NUnit
47 | *.VisualState.xml
48 | TestResult.xml
49 | nunit-*.xml
50 |
51 | # Build Results of an ATL Project
52 | [Dd]ebugPS/
53 | [Rr]eleasePS/
54 | dlldata.c
55 |
56 | # Benchmark Results
57 | BenchmarkDotNet.Artifacts/
58 |
59 | # .NET Core
60 | project.lock.json
61 | project.fragment.lock.json
62 | artifacts/
63 |
64 | # StyleCop
65 | StyleCopReport.xml
66 |
67 | # Files built by Visual Studio
68 | *_i.c
69 | *_p.c
70 | *_h.h
71 | *.ilk
72 | *.meta
73 | *.obj
74 | *.iobj
75 | *.pch
76 | *.pdb
77 | *.ipdb
78 | *.pgc
79 | *.pgd
80 | *.rsp
81 | *.sbr
82 | *.tlb
83 | *.tli
84 | *.tlh
85 | *.tmp
86 | *.tmp_proj
87 | *_wpftmp.csproj
88 | *.log
89 | *.vspscc
90 | *.vssscc
91 | .builds
92 | *.pidb
93 | *.svclog
94 | *.scc
95 |
96 | # Chutzpah Test files
97 | _Chutzpah*
98 |
99 | # Visual C++ cache files
100 | ipch/
101 | *.aps
102 | *.ncb
103 | *.opendb
104 | *.opensdf
105 | *.sdf
106 | *.cachefile
107 | *.VC.db
108 | *.VC.VC.opendb
109 |
110 | # Visual Studio profiler
111 | *.psess
112 | *.vsp
113 | *.vspx
114 | *.sap
115 |
116 | # Visual Studio Trace Files
117 | *.e2e
118 |
119 | # TFS 2012 Local Workspace
120 | $tf/
121 |
122 | # Guidance Automation Toolkit
123 | *.gpState
124 |
125 | # ReSharper is a .NET coding add-in
126 | _ReSharper*/
127 | *.[Rr]e[Ss]harper
128 | *.DotSettings.user
129 |
130 | # TeamCity is a build add-in
131 | _TeamCity*
132 |
133 | # DotCover is a Code Coverage Tool
134 | *.dotCover
135 |
136 | # AxoCover is a Code Coverage Tool
137 | .axoCover/*
138 | !.axoCover/settings.json
139 |
140 | # Visual Studio code coverage results
141 | *.coverage
142 | *.coveragexml
143 |
144 | # NCrunch
145 | _NCrunch_*
146 | .*crunch*.local.xml
147 | nCrunchTemp_*
148 |
149 | # MightyMoose
150 | *.mm.*
151 | AutoTest.Net/
152 |
153 | # Web workbench (sass)
154 | .sass-cache/
155 |
156 | # Installshield output folder
157 | [Ee]xpress/
158 |
159 | # DocProject is a documentation generator add-in
160 | DocProject/buildhelp/
161 | DocProject/Help/*.HxT
162 | DocProject/Help/*.HxC
163 | DocProject/Help/*.hhc
164 | DocProject/Help/*.hhk
165 | DocProject/Help/*.hhp
166 | DocProject/Help/Html2
167 | DocProject/Help/html
168 |
169 | # Click-Once directory
170 | publish/
171 |
172 | # Publish Web Output
173 | *.[Pp]ublish.xml
174 | *.azurePubxml
175 | # Note: Comment the next line if you want to checkin your web deploy settings,
176 | # but database connection strings (with potential passwords) will be unencrypted
177 | *.pubxml
178 | *.publishproj
179 |
180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
181 | # checkin your Azure Web App publish settings, but sensitive information contained
182 | # in these scripts will be unencrypted
183 | PublishScripts/
184 |
185 | # NuGet Packages
186 | *.nupkg
187 | # NuGet Symbol Packages
188 | *.snupkg
189 | # The packages folder can be ignored because of Package Restore
190 | **/[Pp]ackages/*
191 | # except build/, which is used as an MSBuild target.
192 | !**/[Pp]ackages/build/
193 | # Uncomment if necessary however generally it will be regenerated when needed
194 | #!**/[Pp]ackages/repositories.config
195 | # NuGet v3's project.json files produces more ignorable files
196 | *.nuget.props
197 | *.nuget.targets
198 |
199 | # Microsoft Azure Build Output
200 | csx/
201 | *.build.csdef
202 |
203 | # Microsoft Azure Emulator
204 | ecf/
205 | rcf/
206 |
207 | # Windows Store app package directories and files
208 | AppPackages/
209 | BundleArtifacts/
210 | Package.StoreAssociation.xml
211 | _pkginfo.txt
212 | *.appx
213 | *.appxbundle
214 | *.appxupload
215 |
216 | # Visual Studio cache files
217 | # files ending in .cache can be ignored
218 | *.[Cc]ache
219 | # but keep track of directories ending in .cache
220 | !?*.[Cc]ache/
221 |
222 | # Others
223 | ClientBin/
224 | ~$*
225 | *~
226 | *.dbmdl
227 | *.dbproj.schemaview
228 | *.jfm
229 | *.pfx
230 | *.publishsettings
231 | orleans.codegen.cs
232 |
233 | # Including strong name files can present a security risk
234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
235 | #*.snk
236 |
237 | # Since there are multiple workflows, uncomment next line to ignore bower_components
238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
239 | #bower_components/
240 |
241 | # RIA/Silverlight projects
242 | Generated_Code/
243 |
244 | # Backup & report files from converting an old project file
245 | # to a newer Visual Studio version. Backup files are not needed,
246 | # because we have git ;-)
247 | _UpgradeReport_Files/
248 | Backup*/
249 | UpgradeLog*.XML
250 | UpgradeLog*.htm
251 | ServiceFabricBackup/
252 | *.rptproj.bak
253 |
254 | # SQL Server files
255 | *.mdf
256 | *.ldf
257 | *.ndf
258 |
259 | # Business Intelligence projects
260 | *.rdl.data
261 | *.bim.layout
262 | *.bim_*.settings
263 | *.rptproj.rsuser
264 | *- [Bb]ackup.rdl
265 | *- [Bb]ackup ([0-9]).rdl
266 | *- [Bb]ackup ([0-9][0-9]).rdl
267 |
268 | # Microsoft Fakes
269 | FakesAssemblies/
270 |
271 | # GhostDoc plugin setting file
272 | *.GhostDoc.xml
273 |
274 | # Node.js Tools for Visual Studio
275 | .ntvs_analysis.dat
276 | node_modules/
277 |
278 | # Visual Studio 6 build log
279 | *.plg
280 |
281 | # Visual Studio 6 workspace options file
282 | *.opt
283 |
284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
285 | *.vbw
286 |
287 | # Visual Studio LightSwitch build output
288 | **/*.HTMLClient/GeneratedArtifacts
289 | **/*.DesktopClient/GeneratedArtifacts
290 | **/*.DesktopClient/ModelManifest.xml
291 | **/*.Server/GeneratedArtifacts
292 | **/*.Server/ModelManifest.xml
293 | _Pvt_Extensions
294 |
295 | # Paket dependency manager
296 | .paket/paket.exe
297 | paket-files/
298 |
299 | # FAKE - F# Make
300 | .fake/
301 |
302 | # CodeRush personal settings
303 | .cr/personal
304 |
305 | # Python Tools for Visual Studio (PTVS)
306 | __pycache__/
307 | *.pyc
308 |
309 | # Cake - Uncomment if you are using it
310 | # tools/**
311 | # !tools/packages.config
312 |
313 | # Tabs Studio
314 | *.tss
315 |
316 | # Telerik's JustMock configuration file
317 | *.jmconfig
318 |
319 | # BizTalk build output
320 | *.btp.cs
321 | *.btm.cs
322 | *.odx.cs
323 | *.xsd.cs
324 |
325 | # OpenCover UI analysis results
326 | OpenCover/
327 |
328 | # Azure Stream Analytics local run output
329 | ASALocalRun/
330 |
331 | # MSBuild Binary and Structured Log
332 | *.binlog
333 |
334 | # NVidia Nsight GPU debugger configuration file
335 | *.nvuser
336 |
337 | # MFractors (Xamarin productivity tool) working folder
338 | .mfractor/
339 |
340 | # Local History for Visual Studio
341 | .localhistory/
342 |
343 | # BeatPulse healthcheck temp database
344 | healthchecksdb
345 |
346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
347 | MigrationBackup/
348 |
349 | # Ionide (cross platform F# VS Code tools) working folder
350 | .ionide/
351 |
--------------------------------------------------------------------------------
/LazyTask.Test/LazyTask.Test.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.1
5 |
6 | false
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/LazyTask.Test/Tests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Threading;
4 | using System.Threading.Tasks;
5 | using NUnit.Framework;
6 |
7 | namespace LazyTask.Test
8 | {
9 | public class Tests
10 | {
11 | [Test]
12 | [TestCase(false, false)]
13 | [TestCase(false, true)]
14 | [TestCase(true, false)]
15 | [TestCase(true, true)]
16 | public async Task TestBasic(bool asyncWait, bool asyncAction)
17 | {
18 | int counter = 0;
19 |
20 | var lt = LazyAction();
21 | if (asyncWait)
22 | {
23 | await Task.Delay(1);
24 | }
25 | Assert.AreEqual(0, counter);
26 |
27 | int res = await lt;
28 |
29 | Assert.AreEqual(1, counter);
30 | Assert.AreEqual(42, res);
31 |
32 | async LazyTask LazyAction()
33 | {
34 | counter++;
35 | if (asyncAction)
36 | {
37 | await Task.Delay(1);
38 | }
39 | return 42;
40 | }
41 | }
42 |
43 |
44 | [Test]
45 | [TestCase(false, false)]
46 | [TestCase(false, true)]
47 | [TestCase(true, false)]
48 | [TestCase(true, true)]
49 | public async Task TestException(bool asyncWait, bool asyncAction)
50 | {
51 | int counter = 0;
52 |
53 | var lt = LazyAction();
54 | if (asyncWait)
55 | {
56 | await Task.Delay(1);
57 | }
58 | Assert.AreEqual(0, counter);
59 |
60 | Exception ex = null;
61 | try
62 | {
63 | await lt;
64 | }
65 | catch (Exception e)
66 | {
67 | ex = e;
68 | }
69 |
70 | Assert.AreEqual(1, counter);
71 | Assert.NotNull(ex);
72 | Assert.AreEqual("Err", ex.Message);
73 |
74 | async LazyTask LazyAction()
75 | {
76 | counter++;
77 | if (asyncAction)
78 | {
79 | await Task.Delay(1);
80 | }
81 | throw new Exception("Err");
82 | }
83 | }
84 |
85 | [Test]
86 | public void TestMultiThreading()
87 | {
88 | //The test shows that locks are really required in LazyTasks
89 |
90 | int counter = 0;
91 |
92 | ManualResetEvent syncStart = new ManualResetEvent(false);
93 |
94 | const int num = 100;
95 | const int threadsNum = 10;
96 |
97 | for (int i = 0; i < num; i++)
98 | {
99 |
100 | var lt = LazyAction();
101 |
102 | List threads = new List();
103 |
104 | for (int j = 0; j < threadsNum; j++)
105 | {
106 | threads.Add(new Thread(() => ThreadBody(lt)));
107 | }
108 |
109 | foreach (var thread in threads)
110 | {
111 | thread.Start();
112 | }
113 |
114 | syncStart.Set();
115 |
116 | foreach (var thread in threads)
117 | {
118 | thread.Join();
119 | }
120 | }
121 |
122 | Assert.AreEqual(num, counter);
123 |
124 | void ThreadBody(LazyTask lt)
125 | {
126 | AutoResetEvent ev = new AutoResetEvent(false);
127 |
128 | syncStart.WaitOne();
129 |
130 | lt.OnCompleted(() =>
131 | {
132 | Assert.AreEqual(42, lt.GetResult());
133 | ev.Set();
134 | });
135 | ev.WaitOne();
136 | }
137 |
138 | async LazyTask LazyAction()
139 | {
140 | counter++;
141 | await Task.Delay(1);
142 | return 42;
143 | }
144 | }
145 |
146 | }
147 | }
--------------------------------------------------------------------------------
/LazyTask.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30114.105
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LazyTask", "LazyTask\LazyTask.csproj", "{4F06344F-E9E1-4AB3-A979-32DBC544CF5A}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LazyTask.Test", "LazyTask.Test\LazyTask.Test.csproj", "{FE42FE8F-0AB1-4A05-B827-C243F0226CB2}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {4F06344F-E9E1-4AB3-A979-32DBC544CF5A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {4F06344F-E9E1-4AB3-A979-32DBC544CF5A}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {4F06344F-E9E1-4AB3-A979-32DBC544CF5A}.Release|Any CPU.ActiveCfg = Release|Any CPU
19 | {4F06344F-E9E1-4AB3-A979-32DBC544CF5A}.Release|Any CPU.Build.0 = Release|Any CPU
20 | {FE42FE8F-0AB1-4A05-B827-C243F0226CB2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {FE42FE8F-0AB1-4A05-B827-C243F0226CB2}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {FE42FE8F-0AB1-4A05-B827-C243F0226CB2}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {FE42FE8F-0AB1-4A05-B827-C243F0226CB2}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {05EE4180-BFE0-48CA-ACBC-54F3127D8081}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/LazyTask/LazyTask.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.ExceptionServices;
4 |
5 | namespace LazyTask
6 | {
7 | [AsyncMethodBuilder(typeof(LazyTaskMethodBuilder<>))]
8 | public class LazyTask : INotifyCompletion
9 | {
10 | private readonly object _syncObj = new object();
11 |
12 | private T _result;
13 |
14 | private Exception _exception;
15 |
16 | private IAsyncStateMachine _asyncStateMachine;
17 |
18 | private Action _continuation;
19 |
20 | internal LazyTask()
21 | {
22 | }
23 |
24 | public T GetResult()
25 | {
26 | lock (this._syncObj)
27 | {
28 | if (this._exception != null)
29 | {
30 | ExceptionDispatchInfo.Throw(this._exception);
31 | }
32 |
33 | if (!this.IsCompleted)
34 | {
35 | throw new Exception("Not Completed");
36 | }
37 |
38 | return this._result;
39 | }
40 | }
41 |
42 | public bool IsCompleted { get; private set; }
43 |
44 | public void OnCompleted(Action continuation)
45 | {
46 | lock (this._syncObj)
47 | {
48 | if (this._asyncStateMachine != null)
49 | {
50 | try
51 | {
52 | this._asyncStateMachine.MoveNext();
53 | }
54 | finally
55 | {
56 | this._asyncStateMachine = null;
57 | }
58 | }
59 | if (this._continuation == null)
60 | {
61 | this._continuation = continuation;
62 | }
63 | else
64 | {
65 | this._continuation += continuation;
66 | }
67 | this.TryCallContinuation();
68 | }
69 | }
70 |
71 | public LazyTask GetAwaiter() => this;
72 |
73 | internal void SetResult(T result)
74 | {
75 | lock (this._syncObj)
76 | {
77 | this._result = result;
78 | this.IsCompleted = true;
79 | this.TryCallContinuation();
80 | }
81 | }
82 |
83 | internal void SetException(Exception exception)
84 | {
85 | lock (this._syncObj)
86 | {
87 | this._exception = exception;
88 | this.IsCompleted = true;
89 | this.TryCallContinuation();
90 | }
91 | }
92 |
93 | internal void SetStateMachine(IAsyncStateMachine stateMachine)
94 | {
95 | this._asyncStateMachine = stateMachine;
96 | }
97 |
98 | private void TryCallContinuation()
99 | {
100 | if (this.IsCompleted && this._continuation != null)
101 | {
102 | try
103 | {
104 | this._continuation();
105 | }
106 | finally
107 | {
108 | this._continuation = null;
109 | }
110 | }
111 | }
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/LazyTask/LazyTask.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.1
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/LazyTask/LazyTaskMethodBuilder.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.CompilerServices;
3 |
4 | namespace LazyTask
5 | {
6 | public class LazyTaskMethodBuilder
7 | {
8 | public LazyTaskMethodBuilder() => this.Task = new LazyTask();
9 |
10 | public static LazyTaskMethodBuilder Create() => new LazyTaskMethodBuilder();
11 |
12 | public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
13 | {
14 | //instead of stateMachine.MoveNext();
15 | this.Task.SetStateMachine(stateMachine);
16 | }
17 |
18 | public void SetStateMachine(IAsyncStateMachine stateMachine) { }
19 |
20 | public void SetException(Exception exception) => this.Task.SetException(exception);
21 |
22 | public void SetResult(T result) => this.Task.SetResult(result);
23 |
24 | public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine)
25 | where TAwaiter : INotifyCompletion
26 | where TStateMachine : IAsyncStateMachine
27 | =>
28 | this.GenericAwaitOnCompleted(ref awaiter, ref stateMachine);
29 |
30 | public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter,
31 | ref TStateMachine stateMachine)
32 | where TAwaiter : ICriticalNotifyCompletion
33 | where TStateMachine : IAsyncStateMachine
34 | =>
35 | this.GenericAwaitOnCompleted(ref awaiter, ref stateMachine);
36 |
37 | public void GenericAwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine)
38 | where TAwaiter : INotifyCompletion
39 | where TStateMachine : IAsyncStateMachine
40 | {
41 | awaiter.OnCompleted(stateMachine.MoveNext);
42 | }
43 |
44 | public LazyTask Task { get; }
45 | }
46 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # LazyTask
2 | [Writing “Lazy Task” Using New Features of C# 7 (on medium.com)](https://medium.com/@0x1000000/writing-lazy-task-using-new-features-of-c-7-7e9b3f2fda07?source=friends_link&sk=0b5456443aad6b12d0b3f8e117b669bf)
3 |
4 | [Video version with more details](https://youtu.be/zq15I0QB6eM)
5 |
--------------------------------------------------------------------------------