Best Coyote code snippet using Microsoft.Coyote.Actors.Mocks.MockEventQueue.Dispose
ActorExecutionContext.cs
Source:ActorExecutionContext.cs  
...740        }741        /// <inheritdoc/>742        public void Stop() => this.Runtime.Stop();743        /// <summary>744        /// Disposes runtime resources.745        /// </summary>746        protected virtual void Dispose(bool disposing)747        {748            if (disposing)749            {750                this.ActorMap.Clear();751                this.EnabledActors.Clear();752            }753        }754        /// <inheritdoc/>755        public void Dispose()756        {757            this.Dispose(true);758            GC.SuppressFinalize(this);759        }760        /// <summary>761        /// The mocked execution context of an actor program.762        /// </summary>763        internal sealed class Mock : ActorExecutionContext764        {765            /// <summary>766            /// Set of all created actor ids.767            /// </summary>768            private readonly ConcurrentDictionary<ActorId, byte> ActorIds;769            /// <summary>770            /// Map that stores all unique names and their corresponding actor ids.771            /// </summary>772            private readonly ConcurrentDictionary<string, ActorId> NameValueToActorId;773            /// <summary>774            /// Map of program counters used for state-caching to distinguish775            /// scheduling from non-deterministic choices.776            /// </summary>777            private readonly ConcurrentDictionary<ActorId, int> ProgramCounterMap;778            /// <summary>779            /// If true, the actor execution is controlled, else false.780            /// </summary>781            internal override bool IsExecutionControlled => true;782            /// <summary>783            /// Initializes a new instance of the <see cref="Mock"/> class.784            /// </summary>785            internal Mock(Configuration configuration, CoyoteRuntime runtime)786                : base(configuration, runtime)787            {788                this.ActorIds = new ConcurrentDictionary<ActorId, byte>();789                this.NameValueToActorId = new ConcurrentDictionary<string, ActorId>();790                this.ProgramCounterMap = new ConcurrentDictionary<ActorId, int>();791            }792            /// <inheritdoc/>793            public override ActorId CreateActorIdFromName(Type type, string name)794            {795                // It is important that all actor ids use the monotonically incrementing796                // value as the id during testing, and not the unique name.797                var id = this.NameValueToActorId.GetOrAdd(name, key => this.CreateActorId(type, key));798                this.ActorIds.TryAdd(id, 0);799                return id;800            }801            /// <inheritdoc/>802            public override ActorId CreateActor(Type type, Event initialEvent = null, EventGroup eventGroup = null) =>803                this.CreateActor(null, type, null, initialEvent, eventGroup);804            /// <inheritdoc/>805            public override ActorId CreateActor(Type type, string name, Event initialEvent = null, EventGroup eventGroup = null) =>806                this.CreateActor(null, type, name, initialEvent, eventGroup);807            /// <inheritdoc/>808            public override ActorId CreateActor(ActorId id, Type type, Event initialEvent = null, EventGroup eventGroup = null)809            {810                this.Assert(id != null, "Cannot create an actor using a null actor id.");811                return this.CreateActor(id, type, null, initialEvent, eventGroup);812            }813            /// <inheritdoc/>814            public override Task<ActorId> CreateActorAndExecuteAsync(Type type, Event initialEvent = null, EventGroup eventGroup = null) =>815                this.CreateActorAndExecuteAsync(null, type, null, initialEvent, eventGroup);816            /// <inheritdoc/>817            public override Task<ActorId> CreateActorAndExecuteAsync(Type type, string name, Event initialEvent = null, EventGroup eventGroup = null) =>818                this.CreateActorAndExecuteAsync(null, type, name, initialEvent, eventGroup);819            /// <inheritdoc/>820            public override Task<ActorId> CreateActorAndExecuteAsync(ActorId id, Type type, Event initialEvent = null, EventGroup eventGroup = null)821            {822                this.Assert(id != null, "Cannot create an actor using a null actor id.");823                return this.CreateActorAndExecuteAsync(id, type, null, initialEvent, eventGroup);824            }825            /// <summary>826            /// Creates a new actor of the specified <see cref="Type"/> and name, using the specified827            /// unbound actor id, and passes the specified optional <see cref="Event"/>. This event828            /// can only be used to access its payload, and cannot be handled.829            /// </summary>830            internal ActorId CreateActor(ActorId id, Type type, string name, Event initialEvent = null, EventGroup eventGroup = null)831            {832                var creatorOp = this.Runtime.GetExecutingOperation<ActorOperation>();833                return this.CreateActor(id, type, name, initialEvent, creatorOp?.Actor, eventGroup);834            }835            /// <summary>836            /// Creates a new <see cref="Actor"/> of the specified <see cref="Type"/>.837            /// </summary>838            internal override ActorId CreateActor(ActorId id, Type type, string name, Event initialEvent, Actor creator, EventGroup eventGroup)839            {840                this.AssertExpectedCallerActor(creator, "CreateActor");841                Actor actor = this.CreateActor(id, type, name, creator, eventGroup);842                this.OnActorEventHandlerStarted(actor.Id);843                this.RunActorEventHandler(actor, initialEvent, true, null);844                return actor.Id;845            }846            /// <summary>847            /// Creates a new actor of the specified <see cref="Type"/> and name, using the specified848            /// unbound actor id, and passes the specified optional <see cref="Event"/>. This event849            /// can only be used to access its payload, and cannot be handled. The method returns only850            /// when the actor is initialized and the <see cref="Event"/> (if any) is handled.851            /// </summary>852            internal Task<ActorId> CreateActorAndExecuteAsync(ActorId id, Type type, string name, Event initialEvent = null,853                EventGroup eventGroup = null)854            {855                var creatorOp = this.Runtime.GetExecutingOperation<ActorOperation>();856                return this.CreateActorAndExecuteAsync(id, type, name, initialEvent, creatorOp?.Actor, eventGroup);857            }858            /// <summary>859            /// Creates a new <see cref="Actor"/> of the specified <see cref="Type"/>. The method860            /// returns only when the actor is initialized and the <see cref="Event"/> (if any)861            /// is handled.862            /// </summary>863            internal override async Task<ActorId> CreateActorAndExecuteAsync(ActorId id, Type type, string name, Event initialEvent,864                Actor creator, EventGroup eventGroup)865            {866                this.AssertExpectedCallerActor(creator, "CreateActorAndExecuteAsync");867                this.Assert(creator != null, "Only an actor can call 'CreateActorAndExecuteAsync': avoid calling " +868                    "it directly from the test method; instead call it through a test driver actor.");869                Actor actor = this.CreateActor(id, type, name, creator, eventGroup);870                this.OnActorEventHandlerStarted(actor.Id);871                this.RunActorEventHandler(actor, initialEvent, true, creator);872                // Wait until the actor reaches quiescence.873                await creator.ReceiveEventAsync(typeof(QuiescentEvent), rev => (rev as QuiescentEvent).ActorId == actor.Id);874                return await Task.FromResult(actor.Id);875            }876            /// <summary>877            /// Creates a new <see cref="Actor"/> of the specified <see cref="Type"/>.878            /// </summary>879            internal override Actor CreateActor(ActorId id, Type type, string name, Actor creator, EventGroup eventGroup)880            {881                this.Assert(type.IsSubclassOf(typeof(Actor)), "Type '{0}' is not an actor.", type.FullName);882                // Using ulong.MaxValue because a Create operation cannot specify883                // the id of its target, because the id does not exist yet.884                this.Runtime.ScheduleNextOperation(creator?.Operation, SchedulingPointType.Create);885                this.ResetProgramCounter(creator);886                if (id is null)887                {888                    id = this.CreateActorId(type, name);889                    this.ActorIds.TryAdd(id, 0);890                }891                else892                {893                    if (this.ActorMap.ContainsKey(id))894                    {895                        throw new InvalidOperationException($"An actor with id '{id.Value}' already exists.");896                    }897                    this.Assert(id.Runtime is null || id.Runtime == this, "Unbound actor id '{0}' was created by another runtime.", id.Value);898                    this.Assert(id.Type == type.FullName, "Cannot bind actor id '{0}' of type '{1}' to an actor of type '{2}'.",899                        id.Value, id.Type, type.FullName);900                    id.Bind(this);901                }902                // If a group was not provided, inherit the current event group from the creator (if any).903                if (eventGroup is null && creator != null)904                {905                    eventGroup = creator.EventGroup;906                }907                Actor actor = ActorFactory.Create(type);908                ActorOperation op = this.GetOrCreateActorOperation(id, actor);909                IEventQueue eventQueue = new MockEventQueue(actor);910                actor.Configure(this, id, op, eventQueue, eventGroup);911                actor.SetupEventHandlers();912                // This should always succeed, because it is either a new id or it has already passed913                // the assertion check, which still holds due to the schedule serialization during914                // systematic testing, but we still do the check defensively.915                if (!this.ActorMap.TryAdd(id, actor))916                {917                    throw new InvalidOperationException($"An actor with id '{id.Value}' already exists.");918                }919                if (this.Configuration.IsActivityCoverageReported)920                {921                    actor.ReportActivityCoverage(this.CoverageInfo);922                }923                if (actor is StateMachine)924                {925                    this.LogWriter.LogCreateStateMachine(id, creator?.Id.Name, creator?.Id.Type);926                }927                else928                {929                    this.LogWriter.LogCreateActor(id, creator?.Id.Name, creator?.Id.Type);930                }931                return actor;932            }933            /// <inheritdoc/>934            public override void SendEvent(ActorId targetId, Event initialEvent, EventGroup eventGroup = default, SendOptions options = null)935            {936                var senderOp = this.Runtime.GetExecutingOperation<ActorOperation>();937                this.SendEvent(targetId, initialEvent, senderOp?.Actor, eventGroup, options);938            }939            /// <inheritdoc/>940            public override Task<bool> SendEventAndExecuteAsync(ActorId targetId, Event initialEvent,941                EventGroup eventGroup = null, SendOptions options = null)942            {943                var senderOp = this.Runtime.GetExecutingOperation<ActorOperation>();944                return this.SendEventAndExecuteAsync(targetId, initialEvent, senderOp?.Actor, eventGroup, options);945            }946            /// <summary>947            /// Sends an asynchronous <see cref="Event"/> to an actor.948            /// </summary>949            internal override void SendEvent(ActorId targetId, Event e, Actor sender, EventGroup eventGroup, SendOptions options)950            {951                if (e is null)952                {953                    string message = sender != null ?954                        string.Format("{0} is sending a null event.", sender.Id.ToString()) :955                        "Cannot send a null event.";956                    this.Assert(false, message);957                }958                if (sender != null)959                {960                    this.Assert(targetId != null, "{0} is sending event {1} to a null actor.", sender.Id, e);961                }962                else963                {964                    this.Assert(targetId != null, "Cannot send event {1} to a null actor.", e);965                }966                this.AssertExpectedCallerActor(sender, "SendEvent");967                EnqueueStatus enqueueStatus = this.EnqueueEvent(targetId, e, sender, eventGroup, options, out Actor target);968                if (enqueueStatus is EnqueueStatus.EventHandlerNotRunning)969                {970                    this.OnActorEventHandlerStarted(target.Id);971                    this.RunActorEventHandler(target, null, false, null);972                }973            }974            /// <summary>975            /// Sends an asynchronous <see cref="Event"/> to an actor. Returns immediately if the target was976            /// already running. Otherwise blocks until the target handles the event and reaches quiescence.977            /// </summary>978            internal override async Task<bool> SendEventAndExecuteAsync(ActorId targetId, Event e, Actor sender,979                EventGroup eventGroup, SendOptions options)980            {981                this.Assert(sender is StateMachine, "Only an actor can call 'SendEventAndExecuteAsync': avoid " +982                    "calling it directly from the test method; instead call it through a test driver actor.");983                this.Assert(e != null, "{0} is sending a null event.", sender.Id);984                this.Assert(targetId != null, "{0} is sending event {1} to a null actor.", sender.Id, e);985                this.AssertExpectedCallerActor(sender, "SendEventAndExecuteAsync");986                EnqueueStatus enqueueStatus = this.EnqueueEvent(targetId, e, sender, eventGroup, options, out Actor target);987                if (enqueueStatus is EnqueueStatus.EventHandlerNotRunning)988                {989                    this.OnActorEventHandlerStarted(target.Id);990                    this.RunActorEventHandler(target, null, false, sender as StateMachine);991                    // Wait until the actor reaches quiescence.992                    await (sender as StateMachine).ReceiveEventAsync(typeof(QuiescentEvent), rev => (rev as QuiescentEvent).ActorId == targetId);993                    return true;994                }995                // EnqueueStatus.EventHandlerNotRunning is not returned by EnqueueEvent996                // (even when the actor was previously inactive) when the event e requires997                // no action by the actor (i.e., it implicitly handles the event).998                return enqueueStatus is EnqueueStatus.Dropped || enqueueStatus is EnqueueStatus.NextEventUnavailable;999            }1000            /// <summary>1001            /// Enqueues an event to the actor with the specified id.1002            /// </summary>1003            private EnqueueStatus EnqueueEvent(ActorId targetId, Event e, Actor sender, EventGroup eventGroup,1004                SendOptions options, out Actor target)1005            {1006                target = this.Runtime.GetOperationWithId<ActorOperation>(targetId.Value)?.Actor;1007                this.Assert(target != null,1008                    "Cannot send event '{0}' to actor id '{1}' that is not bound to an actor instance.",1009                    e.GetType().FullName, targetId.Value);1010                this.Runtime.ScheduleNextOperation(sender?.Operation, SchedulingPointType.Send);1011                this.ResetProgramCounter(sender as StateMachine);1012                // If no group is provided we default to passing along the group from the sender.1013                if (eventGroup is null && sender != null)1014                {1015                    eventGroup = sender.EventGroup;1016                }1017                if (target.IsHalted)1018                {1019                    Guid groupId = eventGroup is null ? Guid.Empty : eventGroup.Id;1020                    this.LogWriter.LogSendEvent(targetId, sender?.Id.Name, sender?.Id.Type,1021                        (sender as StateMachine)?.CurrentStateName ?? default, e, groupId, isTargetHalted: true);1022                    this.Assert(options is null || !options.MustHandle,1023                        "A must-handle event '{0}' was sent to {1} which has halted.", e.GetType().FullName, targetId);1024                    this.HandleDroppedEvent(e, targetId);1025                    return EnqueueStatus.Dropped;1026                }1027                EnqueueStatus enqueueStatus = this.EnqueueEvent(target, e, sender, eventGroup, options);1028                if (enqueueStatus == EnqueueStatus.Dropped)1029                {1030                    this.HandleDroppedEvent(e, targetId);1031                }1032                return enqueueStatus;1033            }1034            /// <summary>1035            /// Enqueues an event to the actor with the specified id.1036            /// </summary>1037            private EnqueueStatus EnqueueEvent(Actor actor, Event e, Actor sender, EventGroup eventGroup, SendOptions options)1038            {1039                EventOriginInfo originInfo;1040                string stateName = null;1041                if (sender is StateMachine senderStateMachine)1042                {1043                    originInfo = new EventOriginInfo(sender.Id, senderStateMachine.GetType().FullName,1044                        NameResolver.GetStateNameForLogging(senderStateMachine.CurrentState));1045                    stateName = senderStateMachine.CurrentStateName;1046                }1047                else if (sender is Actor senderActor)1048                {1049                    originInfo = new EventOriginInfo(sender.Id, senderActor.GetType().FullName, string.Empty);1050                }1051                else1052                {1053                    // Message comes from the environment.1054                    originInfo = new EventOriginInfo(null, "Env", "Env");1055                }1056                EventInfo eventInfo = new EventInfo(e, originInfo)1057                {1058                    MustHandle = options?.MustHandle ?? false,1059                    Assert = options?.Assert ?? -11060                };1061                Guid opId = eventGroup is null ? Guid.Empty : eventGroup.Id;1062                this.LogWriter.LogSendEvent(actor.Id, sender?.Id.Name, sender?.Id.Type, stateName,1063                    e, opId, isTargetHalted: false);1064                return actor.Enqueue(e, eventGroup, eventInfo);1065            }1066            /// <summary>1067            /// Runs a new asynchronous event handler for the specified actor.1068            /// This is a fire and forget invocation.1069            /// </summary>1070            /// <param name="actor">The actor that executes this event handler.</param>1071            /// <param name="initialEvent">Optional event for initializing the actor.</param>1072            /// <param name="isFresh">If true, then this is a new actor.</param>1073            /// <param name="syncCaller">Caller actor that is blocked for quiescence.</param>1074            private void RunActorEventHandler(Actor actor, Event initialEvent, bool isFresh, Actor syncCaller)1075            {1076                this.Runtime.TaskFactory.StartNew(async state =>1077                {1078                    try1079                    {1080                        if (isFresh)1081                        {1082                            await actor.InitializeAsync(initialEvent);1083                        }1084                        await actor.RunEventHandlerAsync();1085                        if (syncCaller != null)1086                        {1087                            this.EnqueueEvent(syncCaller, new QuiescentEvent(actor.Id), actor, actor.CurrentEventGroup, null);1088                        }1089                        if (!actor.IsHalted)1090                        {1091                            this.ResetProgramCounter(actor);1092                        }1093                    }1094                    catch (Exception ex)1095                    {1096                        this.Runtime.ProcessUnhandledExceptionInOperation(actor.Operation, ex);1097                    }1098                    finally1099                    {1100                        if (actor.IsHalted)1101                        {1102                            this.ActorMap.TryRemove(actor.Id, out Actor _);1103                        }1104                        this.OnActorEventHandlerCompleted(actor.Id);1105                    }1106                },1107                actor.Operation,1108                default,1109                this.Runtime.TaskFactory.CreationOptions | TaskCreationOptions.DenyChildAttach,1110                this.Runtime.TaskFactory.Scheduler);1111            }1112            /// <summary>1113            /// Creates a new timer that sends a <see cref="TimerElapsedEvent"/> to its owner actor.1114            /// </summary>1115            internal override IActorTimer CreateActorTimer(TimerInfo info, Actor owner)1116            {1117                var id = this.CreateActorId(typeof(MockStateMachineTimer));1118                this.CreateActor(id, typeof(MockStateMachineTimer), new TimerSetupEvent(info, owner, this.Configuration.TimeoutDelay));1119                return this.Runtime.GetOperationWithId<ActorOperation>(id.Value).Actor as MockStateMachineTimer;1120            }1121            /// <inheritdoc/>1122            public override EventGroup GetCurrentEventGroup(ActorId currentActorId)1123            {1124                var callerOp = this.Runtime.GetExecutingOperation<ActorOperation>();1125                this.Assert(callerOp != null && currentActorId == callerOp.Actor.Id,1126                    "Trying to access the event group id of {0}, which is not the currently executing actor.",1127                    currentActorId);1128                return callerOp.Actor.CurrentEventGroup;1129            }1130            /// <summary>1131            /// Returns a controlled nondeterministic boolean choice.1132            /// </summary>1133            internal override bool GetNondeterministicBooleanChoice(string callerName, string callerType)1134            {1135                var caller = this.Runtime.GetExecutingOperation<ActorOperation>()?.Actor;1136                if (caller is Actor callerActor)1137                {1138                    this.IncrementActorProgramCounter(callerActor.Id);1139                }1140                return this.Runtime.GetNextNondeterministicBooleanChoice(callerName ?? caller?.Id.Name, callerType ?? caller?.Id.Type);1141            }1142            /// <summary>1143            /// Returns a controlled nondeterministic integer choice.1144            /// </summary>1145            internal override int GetNondeterministicIntegerChoice(int maxValue, string callerName, string callerType)1146            {1147                var caller = this.Runtime.GetExecutingOperation<ActorOperation>()?.Actor;1148                if (caller is Actor callerActor)1149                {1150                    this.IncrementActorProgramCounter(callerActor.Id);1151                }1152                return this.Runtime.GetNextNondeterministicIntegerChoice(maxValue, callerName ?? caller?.Id.Name, callerType ?? caller?.Id.Type);1153            }1154            /// <inheritdoc/>1155            internal override void LogInvokedAction(Actor actor, MethodInfo action, string handlingStateName, string currentStateName) =>1156                this.LogWriter.LogExecuteAction(actor.Id, handlingStateName, currentStateName, action.Name);1157            /// <inheritdoc/>1158            [MethodImpl(MethodImplOptions.AggressiveInlining)]1159            internal override void LogEnqueuedEvent(Actor actor, Event e, EventGroup eventGroup, EventInfo eventInfo) =>1160                this.LogWriter.LogEnqueueEvent(actor.Id, e);1161            /// <inheritdoc/>1162            internal override void LogDequeuedEvent(Actor actor, Event e, EventInfo eventInfo, bool isFreshDequeue)1163            {1164                if (!isFreshDequeue)1165                {1166                    // Skip the scheduling point, as this is the first dequeue of the event handler,1167                    // to avoid unnecessary context switches.1168                    this.Runtime.ScheduleNextOperation(actor.Operation, SchedulingPointType.Receive);1169                    this.ResetProgramCounter(actor);1170                }1171                string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : null;1172                this.LogWriter.LogDequeueEvent(actor.Id, stateName, e);1173            }1174            /// <inheritdoc/>1175            internal override void LogDefaultEventDequeued(Actor actor)1176            {1177                this.Runtime.ScheduleNextOperation(actor.Operation, SchedulingPointType.Receive);1178                this.ResetProgramCounter(actor);1179            }1180            /// <inheritdoc/>1181            internal override void LogRaisedEvent(Actor actor, Event e, EventGroup eventGroup, EventInfo eventInfo)1182            {1183                string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : null;1184                this.LogWriter.LogRaiseEvent(actor.Id, stateName, e);1185            }1186            /// <inheritdoc/>1187            internal override void LogHandleRaisedEvent(Actor actor, Event e)1188            {1189                string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : null;1190                this.LogWriter.LogHandleRaisedEvent(actor.Id, stateName, e);1191            }1192            /// <inheritdoc/>1193            internal override void LogHandleHaltEvent(Actor actor, int inboxSize)1194            {1195                this.Runtime.ScheduleNextOperation(actor.Operation, SchedulingPointType.Halt);1196                this.LogWriter.LogHalt(actor.Id, inboxSize);1197            }1198            /// <inheritdoc/>1199            [MethodImpl(MethodImplOptions.AggressiveInlining)]1200            internal override void LogReceiveCalled(Actor actor) => this.AssertExpectedCallerActor(actor, "ReceiveEventAsync");1201            /// <inheritdoc/>1202            internal override void LogReceivedEvent(Actor actor, Event e, EventInfo eventInfo)1203            {1204                string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : null;1205                this.LogWriter.LogReceiveEvent(actor.Id, stateName, e, wasBlocked: true);1206            }1207            /// <inheritdoc/>1208            internal override void LogReceivedEventWithoutWaiting(Actor actor, Event e, EventInfo eventInfo)1209            {1210                string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : null;1211                this.LogWriter.LogReceiveEvent(actor.Id, stateName, e, wasBlocked: false);1212                this.Runtime.ScheduleNextOperation(actor.Operation, SchedulingPointType.Receive);1213                this.ResetProgramCounter(actor);1214            }1215            /// <inheritdoc/>1216            internal override void LogWaitEvent(Actor actor, IEnumerable<Type> eventTypes)1217            {1218                string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : null;1219                var eventWaitTypesArray = eventTypes.ToArray();1220                if (eventWaitTypesArray.Length is 1)1221                {1222                    this.LogWriter.LogWaitEvent(actor.Id, stateName, eventWaitTypesArray[0]);1223                }1224                else1225                {1226                    this.LogWriter.LogWaitEvent(actor.Id, stateName, eventWaitTypesArray);1227                }1228                this.Runtime.ScheduleNextOperation(actor.Operation, SchedulingPointType.Pause);1229                this.ResetProgramCounter(actor);1230            }1231            /// <inheritdoc/>1232            internal override void LogEventHandlerTerminated(Actor actor, DequeueStatus dequeueStatus)1233            {1234                string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : null;1235                this.LogWriter.LogEventHandlerTerminated(actor.Id, stateName, dequeueStatus);1236            }1237            /// <inheritdoc/>1238            internal override void LogEnteredState(StateMachine stateMachine) =>1239                this.LogWriter.LogStateTransition(stateMachine.Id, stateMachine.CurrentStateName, isEntry: true);1240            /// <inheritdoc/>1241            internal override void LogExitedState(StateMachine stateMachine) =>1242                this.LogWriter.LogStateTransition(stateMachine.Id, stateMachine.CurrentStateName, isEntry: false);1243            /// <inheritdoc/>1244            internal override void LogPopState(StateMachine stateMachine)1245            {1246                this.AssertExpectedCallerActor(stateMachine, "Pop");1247                this.LogWriter.LogPopState(stateMachine.Id, default, stateMachine.CurrentStateName);1248            }1249            /// <inheritdoc/>1250            internal override void LogInvokedOnEntryAction(StateMachine stateMachine, MethodInfo action)1251            {1252                string stateName = stateMachine.CurrentStateName;1253                this.LogWriter.LogExecuteAction(stateMachine.Id, stateName, stateName, action.Name);1254            }1255            /// <inheritdoc/>1256            internal override void LogInvokedOnExitAction(StateMachine stateMachine, MethodInfo action)1257            {1258                string stateName = stateMachine.CurrentStateName;1259                this.LogWriter.LogExecuteAction(stateMachine.Id, stateName, stateName, action.Name);1260            }1261            /// <inheritdoc/>1262            [MethodImpl(MethodImplOptions.AggressiveInlining)]1263            internal override int GetActorProgramCounter(ActorId actorId) =>1264                this.ProgramCounterMap.GetOrAdd(actorId, 0);1265            /// <summary>1266            /// Increments the program counter of the specified actor.1267            /// </summary>1268            [MethodImpl(MethodImplOptions.AggressiveInlining)]1269            private void IncrementActorProgramCounter(ActorId actorId) =>1270                this.ProgramCounterMap.AddOrUpdate(actorId, 1, (id, value) => value + 1);1271            /// <summary>1272            /// Resets the program counter of the specified actor.1273            /// </summary>1274            private void ResetProgramCounter(Actor actor)1275            {1276                if (actor != null)1277                {1278                    this.ProgramCounterMap.AddOrUpdate(actor.Id, 0, (id, value) => 0);1279                }1280            }1281            /// <inheritdoc/>1282#if !DEBUG1283            [DebuggerHidden]1284#endif1285            internal override void AssertExpectedCallerActor(Actor caller, string calledAPI)1286            {1287                if (caller is null)1288                {1289                    return;1290                }1291                var op = this.Runtime.GetExecutingOperation<ActorOperation>();1292                if (op is null)1293                {1294                    return;1295                }1296                this.Assert(op.Actor.Equals(caller), "{0} invoked {1} on behalf of {2}.",1297                    op.Actor.Id, calledAPI, caller.Id);1298            }1299            /// <inheritdoc/>1300            protected override void Dispose(bool disposing)1301            {1302                if (disposing)1303                {1304                    this.NameValueToActorId.Clear();1305                    this.ProgramCounterMap.Clear();1306                    foreach (var id in this.ActorIds)1307                    {1308                        // Unbind the runtime to avoid memory leaks if the user holds the id.1309                        id.Key.Bind(null);1310                    }1311                    this.ActorIds.Clear();1312                }1313                base.Dispose(disposing);1314            }1315        }1316    }1317}...MockEventQueue.cs
Source:MockEventQueue.cs  
...358        {359            this.IsClosed = true;360        }361        /// <summary>362        /// Disposes the queue resources.363        /// </summary>364        private void Dispose(bool disposing)365        {366            if (!disposing)367            {368                return;369            }370            foreach (var (e, g, info) in this.Queue)371            {372                this.OnDropEvent(e, g, info);373            }374            this.Queue.Clear();375        }376        /// <inheritdoc/>377        public void Dispose()378        {379            this.Dispose(true);380            GC.SuppressFinalize(this);381        }382    }383}...Dispose
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Coyote;4using Microsoft.Coyote.Actors;5using Microsoft.Coyote.Actors.Mocks;6using Microsoft.Coyote.TestingServices;7using Microsoft.Coyote.TestingServices.Coverage;8using Microsoft.Coyote.TestingServices.SchedulingStrategies;9using Microsoft.Coyote.TestingServices.Runtime;10using Microsoft.Coyote.TestingServices.StateCaching;11using Microsoft.Coyote.TestingServices.StateCaching.Strategies;12using Microsoft.Coyote.TestingServices.StateCaching.StateProviders;13using Microsoft.Coyote.TestingServices.StateCaching.StateProviders.Default;14using Microsoft.Coyote.TestingServices.StateCaching.StateProviders.Default.Strategies;15using Microsoft.Coyote.TestingServices.StateCaching.StateProviders.Default.Strategies.TraversalStrategies;16using Microsoft.Coyote.TestingServices.StateCaching.StateProviders.Default.Strategies.TraversalStrategies.Default;17using Microsoft.Coyote.TestingServices.StateCaching.StateProviders.Default.Strategies.TraversalStrategies.Default.Strategies;18using Microsoft.Coyote.TestingServices.StateCaching.StateProviders.Default.Strategies.TraversalStrategies.Default.Strategies.Default;19using Microsoft.Coyote.TestingServices.StateCaching.StateProviders.Default.Strategies.TraversalStrategies.Default.Strategies.Default.Strategies;20using Microsoft.Coyote.TestingServices.StateCaching.StateProviders.Default.Strategies.TraversalStrategies.Default.Strategies.Default.Strategies.Default;21using Microsoft.Coyote.TestingServices.StateCaching.StateProviders.Default.Strategies.TraversalStrategies.Default.Strategies.Default.Strategies.Default.Strategies;22using Microsoft.Coyote.TestingServices.StateCaching.StateProviders.Default.Strategies.TraversalStrategies.Default.Strategies.Default.Strategies.Default.Strategies.Default;23using Microsoft.Coyote.TestingServices.StateCaching.StateProviders.Default.Strategies.TraversalStrategies.Default.Strategies.Default.Strategies.Default.Strategies.Default.Strategies;24using Microsoft.Coyote.TestingServices.StateCaching.StateProviders.Default.Strategies.TraversalStrategies.Default.Strategies.Default.Strategies.Default.Strategies.Default.Strategies.Default;25using Microsoft.Coyote.TestingServices.StateCaching.StateProviders.Default.Strategies.TraversalStrategies.Default.Strategies.Default.Strategies.Default.Strategies.Default.Strategies.Default.Strategies;26using Microsoft.Coyote.TestingServices.StateCaching.StateProviders.Default.Strategies.TraversalStrategies.Default.Strategies.Default.Strategies.Default.Strategies.Default.Strategies.Default.Strategies.Default;Dispose
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Coyote.Actors;4using Microsoft.Coyote.Actors.Mocks;5using Microsoft.Coyote.Specifications;6using Microsoft.Coyote.SystematicTesting;7using Microsoft.Coyote.Tasks;8{9    {10        static async Task Main(string[] args)11        {12            using (var runtime = TestingEngine.Create())13            {14                var config = Configuration.Create();15                config.MaxSchedulingSteps = 1000;16                config.MaxFairSchedulingSteps = 1000;17                config.MaxUnfairSchedulingSteps = 1000;18                config.EnableCycleDetection = true;19                config.EnableDataRaceDetection = true;20                config.EnableIntegerOverflowDetection = true;21                config.EnableDeadlockDetection = true;22                config.EnableLivelockDetection = true;23                config.EnableOperationCanceledException = true;24                config.EnableObjectDisposedException = true;25                config.EnableActorDeadlockException = true;26                runtime.SetConfiguration(config);27                runtime.CreateActor(typeof(Monitor));28                runtime.CreateActor(typeof(Actor1));29                runtime.CreateActor(typeof(Actor2));30                runtime.CreateActor(typeof(Actor3));31                var test = runtime.CreateActor(typeof(Tester));32                var monitor = runtime.GetMonitor<Monitor>();33                monitor.SetTest(test);34                await runtime.StartAsync();35            }36        }37    }38    {39        private ActorId test;40        [OnEventDoAction(typeof(Actor1), nameof(Actor1))]41        [OnEventDoAction(typeof(Actor2), nameof(Actor2))]42        [OnEventDoAction(typeof(Actor3), nameof(Actor3))]43        {44        }45        private void Actor1()46        {47            this.Assert(this.test != null, "Actor1");48            this.SendEvent(this.test, new Actor1());49        }50        private void Actor2()51        {52            this.Assert(this.test != null, "Actor2");53            this.SendEvent(this.test, new Actor2());54        }55        private void Actor3()56        {57            this.Assert(this.test != null, "Actor3");58            this.SendEvent(this.test, new Actor3());59        }60        public void SetTest(ActorId test)61        {62            this.test = test;63        }64    }65    {Dispose
Using AI Code Generation
1using Microsoft.Coyote.Actors.Mocks;2{3    {4        static void Main(string[] args)5        {6            MockEventQueue eventQueue = new MockEventQueue();7            eventQueue.Dispose();8        }9    }10}11using Microsoft.Coyote.Actors.Mocks;12{13    {14        static void Main(string[] args)15        {16            MockActorRuntime runtime = new MockActorRuntime();17            runtime.Dispose();18        }19    }20}21using Microsoft.Coyote.Actors.Mocks;22{23    {24        static void Main(string[] args)25        {26            MockActorManager manager = new MockActorManager();27            manager.Dispose();28        }29    }30}31using Microsoft.Coyote.Actors.Mocks;32{33    {34        static void Main(string[] args)35        {36            MockActor actor = new MockActor();37            actor.Dispose();38        }39    }40}41using Microsoft.Coyote.Actors.Mocks;42{43    {44        static void Main(string[] args)45        {46            MockActorMailbox mailbox = new MockActorMailbox();47            mailbox.Dispose();48        }49    }50}51using Microsoft.Coyote.Actors.Mocks;52{53    {54        static void Main(string[] args)55        {56            MockActorScheduler scheduler = new MockActorScheduler();57            scheduler.Dispose();58        }59    }60}61using Microsoft.Coyote.Actors.Mocks;62{63    {Dispose
Using AI Code Generation
1using System;2using Microsoft.Coyote.Actors.Mocks;3using Microsoft.Coyote.Actors;4using Microsoft.Coyote.Specifications;5using Microsoft.Coyote.Tests.Common;6using Microsoft.Coyote.Tasks;7using Microsoft.Coyote.Tests.Common.Actors;8using System.Threading.Tasks;9using System.Collections.Generic;10using System.Linq;11using System.Threading;12using System.Diagnostics;13using System.Text;14using System.IO;15{16    {17        public static void Main()18        {19            var q = new MockEventQueue();20            q.Dispose();21        }22    }23}24using System;25using Microsoft.Coyote.Actors.Mocks;26using Microsoft.Coyote.Actors;27using Microsoft.Coyote.Specifications;28using Microsoft.Coyote.Tests.Common;29using Microsoft.Coyote.Tasks;30using Microsoft.Coyote.Tests.Common.Actors;31using System.Threading.Tasks;32using System.Collections.Generic;33using System.Linq;34using System.Threading;35using System.Diagnostics;36using System.Text;37using System.IO;38{39    {40        public static void Main()41        {42            var q = new MockActorRuntime();43            q.Dispose();44        }45    }46}47using System;48using Microsoft.Coyote.Actors.Mocks;49using Microsoft.Coyote.Actors;50using Microsoft.Coyote.Specifications;51using Microsoft.Coyote.Tests.Common;52using Microsoft.Coyote.Tasks;53using Microsoft.Coyote.Tests.Common.Actors;54using System.Threading.Tasks;55using System.Collections.Generic;56using System.Linq;57using System.Threading;58using System.Diagnostics;59using System.Text;60using System.IO;61{62    {63        public static void Main()64        {65            var q = new MockActorRuntime();66            q.Dispose();67        }68    }69}70using System;71using Microsoft.Coyote.Actors.Mocks;72using Microsoft.Coyote.Actors;73using Microsoft.Coyote.Specifications;74using Microsoft.Coyote.Tests.Common;75using Microsoft.Coyote.Tasks;Dispose
Using AI Code Generation
1using Microsoft.Coyote.Actors.Mocks;2using Microsoft.Coyote.Actors;3using System;4{5    {6        public static void Main(string[] args)7        {8            using (var runtime = RuntimeFactory.Create())9            {10                var queue = new MockEventQueue();11                queue.Enqueue(new Event());12                queue.Dispose();13            }14        }15    }16}17using Microsoft.Coyote.Actors;18using System;19{20    {21        public static void Main(string[] args)22        {23            using (var runtime = RuntimeFactory.Create())24            {25                runtime.Dispose();26            }27        }28    }29}30using Microsoft.Coyote.Actors;31using System;32{33    {34        public static void Main(string[] args)35        {36            using (var runtime = RuntimeFactory.Create())37            {38                runtime.Dispose();39            }40        }41    }42}43using Microsoft.Coyote.Actors;44using System;45{46    {47        public static void Main(string[] args)48        {49            using (var runtime = RuntimeFactory.Create())50            {51                runtime.Dispose();52            }53        }54    }55}56using Microsoft.Coyote.Actors;57using System;58{59    {60        public static void Main(string[] args)61        {62            using (var runtime = RuntimeFactory.Create())63            {64                runtime.Dispose();65            }66        }67    }68}69using Microsoft.Coyote.Actors;70using System;71{72    {73        public static void Main(string[] args)74        {75            using (var runtime = RuntimeFactory.Create())76            {77                runtime.Dispose();78            }79        }80    }81}Dispose
Using AI Code Generation
1using Microsoft.Coyote.Actors.Mocks;2using System;3{4    {5        static void Main(string[] args)6        {7            var queue = new MockEventQueue();8            queue.Enqueue(new MyEvent());9            var e = queue.Dequeue();10            Console.WriteLine(e.ToString());11            queue.Dispose();12        }13    }14}15using Microsoft.Coyote.Actors.Mocks;16using System;17{18    {19        static void Main(string[] args)20        {21            var mailbox = new MockMailbox();22            mailbox.SendEvent(new MyEvent());23            var e = mailbox.ReceiveEvent();24            Console.WriteLine(e.ToString());25            mailbox.Dispose();26        }27    }28}29using Microsoft.Coyote.Actors.Mocks;30using System;31{32    {33        static void Main(string[] args)34        {35            var runtime = new MockActorRuntime();36            runtime.CreateActor(typeof(MyActor));37            runtime.SendEvent(new MyEvent());38            runtime.Dispose();39        }40    }41}42using Microsoft.Coyote.Actors.Mocks;43using System;44{45    {46        static void Main(string[] args)47        {48            var runtime = new MockActorRuntime();49            var actor = runtime.CreateActor(typeof(MyActor));50            runtime.SendEvent(actor, new MyEvent());51            runtime.Dispose();52        }53    }54}55using Microsoft.Coyote.Actors.Mocks;56using System;57{58    {59        static void Main(string[] args)60        {61            var runtime = new MockActorRuntime();62            var actor = runtime.CreateActor(typeof(MyActor));63            runtime.SendEvent(new MyEvent());64            runtime.Dispose();65        }66    }67}Dispose
Using AI Code Generation
1using Microsoft.Coyote.Actors.Mocks;2using System;3{4    {5        private static void Main(string[] args)6        {7            var mockRuntime = new MockRuntime();8            var mockEventQueue = new MockEventQueue(mockRuntime);9            mockEventQueue.Dispose();10        }11    }12}13using Microsoft.Coyote.Actors.Mocks;14using System;15{16    {17        private static void Main(string[] args)18        {19            var mockRuntime = new MockRuntime();20            var mockEventQueue = new MockEventQueue(mockRuntime);21            mockEventQueue.Dispose();22        }23    }24}25using Microsoft.Coyote.Actors.Mocks;26using System;27{28    {29        private static void Main(string[] args)30        {31            var mockRuntime = new MockRuntime();32            var mockEventQueue = new MockEventQueue(mockRuntime);33            mockEventQueue.Dispose();34        }35    }36}37using Microsoft.Coyote.Actors.Mocks;38using System;39{40    {41        private static void Main(string[] args)42        {43            var mockRuntime = new MockRuntime();44            var mockEventQueue = new MockEventQueue(mockRuntime);45            mockEventQueue.Dispose();46        }47    }48}49using Microsoft.Coyote.Actors.Mocks;50using System;51{52    {53        private static void Main(string[] args)54        {55            var mockRuntime = new MockRuntime();56            var mockEventQueue = new MockEventQueue(mockRuntime);57            mockEventQueue.Dispose();58        }59    }60}61using Microsoft.Coyote.Actors.Mocks;62using System;Dispose
Using AI Code Generation
1using System;2using Microsoft.Coyote.Actors.Mocks;3using Microsoft.Coyote.Actors;4using Microsoft.Coyote.Runtime;5using Microsoft.Coyote.TestingServices;6{7    {8        static void Main(string[] args)9        {10            var runtime = RuntimeFactory.Create();11            var testEngine = new CoyoteTestingEngine(runtime);12            var eventQueue = new MockEventQueue(runtime);13            var actor = new MockActor(runtime, eventQueue, new ActorId(1, "1"), "Actor1");14            var actor2 = new MockActor(runtime, eventQueue, new ActorId(2, "2"), "Actor2");15            eventQueue.Dispose();16            testEngine.Dispose();17        }18    }19}Dispose
Using AI Code Generation
1using System;2{3    {4        static void Main(string[] args)5        {6            Console.WriteLine("Hello World!");7            using (var eventQueue = new Microsoft.Coyote.Actors.Mocks.MockEventQueue())8            {9                eventQueue.Enqueue(new Microsoft.Coyote.Actors.Mocks.MockEvent());10            }11        }12    }13}14using System;15{16    {17        static void Main(string[] args)18        {19            Console.WriteLine("Hello World!");20            using (var eventQueue = new Microsoft.Coyote.Actors.Mocks.MockEventQueue())21            {22                eventQueue.Enqueue(new Microsoft.Coyote.Actors.Mocks.MockEvent());23            }24        }25    }26}27using System;28{29    {30        static void Main(string[] args)31        {32            Console.WriteLine("Hello World!");33            using (var eventQueue = new Microsoft.Coyote.Actors.Mocks.MockEventQueue())34            {35                eventQueue.Enqueue(new Microsoft.Coyote.Actors.Mocks.MockEvent());36            }37        }38    }39}40using System;41{42    {43        static void Main(string[] args)44        {45            Console.WriteLine("Hello World!");46            using (var eventQueue = new Microsoft.Coyote.Actors.Mocks.MockEventQueue())47            {48                eventQueue.Enqueue(new Microsoft.Coyote.Actors.Mocks.MockEvent());49            }50        }51    }52}53using System;54{55    {Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
