diff --git a/src/core/Akka.TestKit/ActorCellKeepingSynchronizationContext.cs b/src/core/Akka.TestKit/ActorCellKeepingSynchronizationContext.cs index 68e42437da8..80fc5e63e0f 100644 --- a/src/core/Akka.TestKit/ActorCellKeepingSynchronizationContext.cs +++ b/src/core/Akka.TestKit/ActorCellKeepingSynchronizationContext.cs @@ -22,8 +22,6 @@ namespace Akka.TestKit class ActorCellKeepingSynchronizationContext : SynchronizationContext { private readonly ActorCell _cell; - - internal static ActorCell AsyncCache { get; set; } /// /// TBD @@ -46,7 +44,8 @@ public override void Post(SendOrPostCallback d, object state) var oldCell = InternalCurrentActorCellKeeper.Current; var oldContext = Current; SetSynchronizationContext(this); - InternalCurrentActorCellKeeper.Current = AsyncCache ?? _cell; + + InternalCurrentActorCellKeeper.Current = _cell; try { diff --git a/src/core/Akka.TestKit/CallingThreadDispatcher.cs b/src/core/Akka.TestKit/CallingThreadDispatcher.cs index e5cd34cb561..68727832df7 100644 --- a/src/core/Akka.TestKit/CallingThreadDispatcher.cs +++ b/src/core/Akka.TestKit/CallingThreadDispatcher.cs @@ -6,6 +6,7 @@ //----------------------------------------------------------------------- using System; +using System.Threading; using Akka.Configuration; using Akka.Dispatch; @@ -53,7 +54,22 @@ public CallingThreadDispatcher(MessageDispatcherConfigurator configurator) : bas protected override void ExecuteTask(IRunnable run) { - run.Run(); + var currentSyncContext = SynchronizationContext.Current; + + try + { + // Actors should not run with ActorCellKeepingSynchronizationContext + // (or any sync context that wraps ActorCellKeepingSynchronizationContext, e.g. Xunit's AsyncTestSyncContext) + // otherwise continuations in async message handlers will use ActorCellKeepingSynchronizationContext + // instead of ActorTaskScheduler which causes ActorContext to be incorrect. + SynchronizationContext.SetSynchronizationContext(null); + + run.Run(); + } + finally + { + SynchronizationContext.SetSynchronizationContext(currentSyncContext); + } } protected override void Shutdown() diff --git a/src/core/Akka.TestKit/Internal/InternalTestActorRef.cs b/src/core/Akka.TestKit/Internal/InternalTestActorRef.cs index bac4c89709d..a386cf8787f 100644 --- a/src/core/Akka.TestKit/Internal/InternalTestActorRef.cs +++ b/src/core/Akka.TestKit/Internal/InternalTestActorRef.cs @@ -323,18 +323,6 @@ internal TestActorTaskScheduler(ActorCell testActorCell, Action - protected override void OnBeforeTaskStarted() - { - ActorCellKeepingSynchronizationContext.AsyncCache = _testActorCell; - } - - /// - protected override void OnAfterTaskCompleted() - { - ActorCellKeepingSynchronizationContext.AsyncCache = null; - } - public void OnTaskCompleted(object message, Exception exception) { _taskCallback(message, exception);