diff --git a/MemoizR.Reactive/Reaction.cs b/MemoizR.Reactive/Reaction.cs index b9db515..3027f39 100644 --- a/MemoizR.Reactive/Reaction.cs +++ b/MemoizR.Reactive/Reaction.cs @@ -16,8 +16,7 @@ internal Reaction(Func fn, Context context, TaskScheduler? sheduler = null this.State = CacheState.CacheDirty; this.label = label; - // The reaction must be initialized to build the Sources. - Update().GetAwaiter().GetResult(); + _ = Init(); } public void Pause() @@ -31,6 +30,15 @@ public Task Resume() return UpdateIfNecessary(); } + private async Task Init() + { + using (await context.contextLock.UpgradeableLockAsync()) + { + // The reaction must be initialized to build the Sources. + await Update(); + } + } + // Update the reaction if dirty, or a parent turns out to be dirty. internal async Task UpdateIfNecessary() { @@ -77,7 +85,7 @@ private async Task Update() State = CacheState.CacheDirty; return; } - + // Evaluate the reactive function body, dynamically capturing any other reactives used. var prevReaction = context.CurrentReaction; var prevGets = context.CurrentGets; @@ -91,7 +99,7 @@ private async Task Update() { if (!isPaused) { - var t = sheduler != null + var t = sheduler != null && sheduler.Id != Thread.CurrentThread.ManagedThreadId ? Task.Factory.StartNew(async () => await fn(), CancellationToken.None, TaskCreationOptions.None, sheduler) : fn(); @@ -122,7 +130,7 @@ private async Task Update() var source = Sources[i]; if (!source.Observers.Any()) { - source.Observers = (new[] { this }).ToArray(); + source.Observers = new[] { this }; } else { diff --git a/MemoizR.StructuredConcurrency/ConcurrentMapReduce.cs b/MemoizR.StructuredConcurrency/ConcurrentMapReduce.cs index 4a1629c..ac1a85a 100644 --- a/MemoizR.StructuredConcurrency/ConcurrentMapReduce.cs +++ b/MemoizR.StructuredConcurrency/ConcurrentMapReduce.cs @@ -127,7 +127,7 @@ private async Task Update() var source = Sources[i]; if (!source.Observers.Any()) { - source.Observers = (new[] { this }).ToArray(); + source.Observers = new[] { this }; } else { diff --git a/MemoizR.StructuredConcurrency/StructuredJobBase.cs b/MemoizR.StructuredConcurrency/StructuredJobBase.cs index 9a478fd..52ec461 100644 --- a/MemoizR.StructuredConcurrency/StructuredJobBase.cs +++ b/MemoizR.StructuredConcurrency/StructuredJobBase.cs @@ -24,7 +24,7 @@ public async Task Run() AddConcurrentWork(); tasks = this.tasks; } - await Task.WhenAll(tasks.ToArray()); + await Task.WhenAll(tasks); return result!; } catch diff --git a/MemoizR/MemoizR.cs b/MemoizR/MemoizR.cs index 2001066..876f389 100644 --- a/MemoizR/MemoizR.cs +++ b/MemoizR/MemoizR.cs @@ -124,7 +124,7 @@ private async Task Update() var source = Sources[i]; if (!source.Observers.Any()) { - source.Observers = (new[] { this }).ToArray(); + source.Observers = new[] { this }; } else {