How to use OnActorEventHandlerStarted method of Microsoft.Coyote.Actors.ActorExecutionContext class

Best Coyote code snippet using Microsoft.Coyote.Actors.ActorExecutionContext.OnActorEventHandlerStarted

ActorExecutionContext.cs

Source:ActorExecutionContext.cs Github

copy

Full Screen

...155 else156 {157 this.LogWriter.LogCreateActor(actor.Id, creator?.Id.Name, creator?.Id.Type);158 }159 this.OnActorEventHandlerStarted(actor.Id);160 this.RunActorEventHandler(actor, initialEvent, true);161 return actor.Id;162 }163 /// <summary>164 /// Creates a new <see cref="Actor"/> of the specified <see cref="Type"/>. The method165 /// returns only when the actor is initialized and the <see cref="Event"/> (if any)166 /// is handled.167 /// </summary>168 internal virtual async Task<ActorId> CreateActorAndExecuteAsync(ActorId id, Type type, string name, Event initialEvent,169 Actor creator, EventGroup eventGroup)170 {171 Actor actor = this.CreateActor(id, type, name, creator, eventGroup);172 if (actor is StateMachine)173 {174 this.LogWriter.LogCreateStateMachine(actor.Id, creator?.Id.Name, creator?.Id.Type);175 }176 else177 {178 this.LogWriter.LogCreateActor(actor.Id, creator?.Id.Name, creator?.Id.Type);179 }180 this.OnActorEventHandlerStarted(actor.Id);181 await this.RunActorEventHandlerAsync(actor, initialEvent, true);182 return actor.Id;183 }184 /// <summary>185 /// Creates a new <see cref="Actor"/> of the specified <see cref="Type"/>.186 /// </summary>187 internal virtual Actor CreateActor(ActorId id, Type type, string name, Actor creator, EventGroup eventGroup)188 {189 if (!type.IsSubclassOf(typeof(Actor)))190 {191 this.Assert(false, "Type '{0}' is not an actor.", type.FullName);192 }193 if (id is null)194 {195 id = this.CreateActorId(type, name);196 }197 else if (id.Runtime != null && id.Runtime != this)198 {199 this.Assert(false, "Unbound actor id '{0}' was created by another runtime.", id.Value);200 }201 else if (id.Type != type.FullName)202 {203 this.Assert(false, "Cannot bind actor id '{0}' of type '{1}' to an actor of type '{2}'.",204 id.Value, id.Type, type.FullName);205 }206 else207 {208 id.Bind(this);209 }210 // If no event group is provided then inherit the current group from the creator.211 if (eventGroup is null && creator != null)212 {213 eventGroup = creator.EventGroup;214 }215 Actor actor = ActorFactory.Create(type);216 ActorOperation op = this.Runtime.SchedulingPolicy is SchedulingPolicy.Fuzzing ?217 this.GetOrCreateActorOperation(id, actor) : null;218 IEventQueue eventQueue = new EventQueue(actor);219 actor.Configure(this, id, op, eventQueue, eventGroup);220 actor.SetupEventHandlers();221 if (!this.ActorMap.TryAdd(id, actor))222 {223 throw new InvalidOperationException($"An actor with id '{id.Value}' already exists.");224 }225 return actor;226 }227 /// <summary>228 /// Returns the operation for the specified actor id, or creates a new229 /// operation if it does not exist yet.230 /// </summary>231 protected ActorOperation GetOrCreateActorOperation(ActorId id, Actor actor)232 {233 var op = this.Runtime.GetOperationWithId<ActorOperation>(id.Value);234 return op ?? new ActorOperation(id.Value, id.Name, actor, this.Runtime);235 }236 /// <inheritdoc/>237 public virtual void SendEvent(ActorId targetId, Event initialEvent, EventGroup eventGroup = default, SendOptions options = null) =>238 this.SendEvent(targetId, initialEvent, null, eventGroup, options);239 /// <inheritdoc/>240 public virtual Task<bool> SendEventAndExecuteAsync(ActorId targetId, Event initialEvent,241 EventGroup eventGroup = null, SendOptions options = null) =>242 this.SendEventAndExecuteAsync(targetId, initialEvent, null, eventGroup, options);243 /// <summary>244 /// Sends an asynchronous <see cref="Event"/> to an actor.245 /// </summary>246 internal virtual void SendEvent(ActorId targetId, Event e, Actor sender, EventGroup eventGroup, SendOptions options)247 {248 EnqueueStatus enqueueStatus = this.EnqueueEvent(targetId, e, sender, eventGroup, out Actor target);249 if (enqueueStatus is EnqueueStatus.EventHandlerNotRunning)250 {251 this.OnActorEventHandlerStarted(target.Id);252 this.RunActorEventHandler(target, null, false);253 }254 }255 /// <summary>256 /// Sends an asynchronous <see cref="Event"/> to an actor. Returns immediately if the target was257 /// already running. Otherwise blocks until the target handles the event and reaches quiescence.258 /// </summary>259 internal virtual async Task<bool> SendEventAndExecuteAsync(ActorId targetId, Event e, Actor sender,260 EventGroup eventGroup, SendOptions options)261 {262 EnqueueStatus enqueueStatus = this.EnqueueEvent(targetId, e, sender, eventGroup, out Actor target);263 if (enqueueStatus is EnqueueStatus.EventHandlerNotRunning)264 {265 this.OnActorEventHandlerStarted(target.Id);266 await this.RunActorEventHandlerAsync(target, null, false);267 return true;268 }269 return enqueueStatus is EnqueueStatus.Dropped;270 }271 /// <summary>272 /// Enqueues an event to the actor with the specified id.273 /// </summary>274 private EnqueueStatus EnqueueEvent(ActorId targetId, Event e, Actor sender, EventGroup eventGroup, out Actor target)275 {276 if (e is null)277 {278 string message = sender != null ?279 string.Format("{0} is sending a null event.", sender.Id.ToString()) :280 "Cannot send a null event.";281 this.Assert(false, message);282 }283 if (targetId is null)284 {285 string message = (sender != null) ?286 string.Format("{0} is sending event {1} to a null actor.", sender.Id.ToString(), e.ToString())287 : string.Format("Cannot send event {0} to a null actor.", e.ToString());288 this.Assert(false, message);289 }290 if (this.Runtime.SchedulingPolicy is SchedulingPolicy.Fuzzing &&291 this.Runtime.TryGetExecutingOperation(out ControlledOperation current))292 {293 this.Runtime.DelayOperation(current);294 }295 target = this.GetActorWithId<Actor>(targetId);296 // If no group is provided we default to passing along the group from the sender.297 if (eventGroup is null && sender != null)298 {299 eventGroup = sender.EventGroup;300 }301 Guid opId = eventGroup is null ? Guid.Empty : eventGroup.Id;302 if (target is null || target.IsHalted)303 {304 this.LogWriter.LogSendEvent(targetId, sender?.Id.Name, sender?.Id.Type,305 (sender as StateMachine)?.CurrentStateName ?? default, e, opId, isTargetHalted: true);306 this.HandleDroppedEvent(e, targetId);307 return EnqueueStatus.Dropped;308 }309 this.LogWriter.LogSendEvent(targetId, sender?.Id.Name, sender?.Id.Type,310 (sender as StateMachine)?.CurrentStateName ?? default, e, opId, isTargetHalted: false);311 EnqueueStatus enqueueStatus = target.Enqueue(e, eventGroup, null);312 if (enqueueStatus == EnqueueStatus.Dropped)313 {314 this.HandleDroppedEvent(e, targetId);315 }316 return enqueueStatus;317 }318 /// <summary>319 /// Runs a new asynchronous actor event handler.320 /// This is a fire and forget invocation.321 /// </summary>322 private void RunActorEventHandler(Actor actor, Event initialEvent, bool isFresh)323 {324 if (this.Runtime.SchedulingPolicy is SchedulingPolicy.Fuzzing)325 {326 this.Runtime.TaskFactory.StartNew(async state =>327 {328 await this.RunActorEventHandlerAsync(actor, initialEvent, isFresh);329 },330 actor.Operation,331 default,332 this.Runtime.TaskFactory.CreationOptions | TaskCreationOptions.DenyChildAttach,333 this.Runtime.TaskFactory.Scheduler);334 }335 else336 {337 Task.Run(async () => await this.RunActorEventHandlerAsync(actor, initialEvent, isFresh));338 }339 }340 /// <summary>341 /// Runs a new asynchronous actor event handler.342 /// </summary>343 private async Task RunActorEventHandlerAsync(Actor actor, Event initialEvent, bool isFresh)344 {345 try346 {347 if (isFresh)348 {349 await actor.InitializeAsync(initialEvent);350 }351 await actor.RunEventHandlerAsync();352 }353 catch (Exception ex)354 {355 this.Runtime.IsRunning = false;356 this.RaiseOnFailureEvent(ex);357 }358 finally359 {360 if (actor.IsHalted)361 {362 this.ActorMap.TryRemove(actor.Id, out Actor _);363 }364 this.OnActorEventHandlerCompleted(actor.Id);365 }366 }367 /// <summary>368 /// Invoked when the event handler of the specified actor starts.369 /// </summary>370 protected void OnActorEventHandlerStarted(ActorId actorId)371 {372 if (this.Runtime.SchedulingPolicy != SchedulingPolicy.None)373 {374 lock (this.QuiescenceSyncObject)375 {376 this.EnabledActors.Add(actorId);377 }378 }379 }380 /// <summary>381 /// Invoked when the event handler of the specified actor completes.382 /// </summary>383 protected void OnActorEventHandlerCompleted(ActorId actorId)384 {385 if (this.Runtime.SchedulingPolicy != SchedulingPolicy.None)386 {387 lock (this.QuiescenceSyncObject)388 {389 this.EnabledActors.Remove(actorId);390 if (this.IsActorQuiescenceAwaited && this.EnabledActors.Count is 0)391 {392 this.QuiescenceCompletionSource.TrySetResult(true);393 }394 }395 }396 }397 /// <summary>398 /// Creates a new timer that sends a <see cref="TimerElapsedEvent"/> to its owner actor.399 /// </summary>400 internal virtual IActorTimer CreateActorTimer(TimerInfo info, Actor owner) => new ActorTimer(info, owner);401 /// <inheritdoc/>402 public virtual EventGroup GetCurrentEventGroup(ActorId currentActorId)403 {404 Actor actor = this.GetActorWithId<Actor>(currentActorId);405 return actor?.CurrentEventGroup;406 }407 /// <summary>408 /// Gets the actor of type <typeparamref name="TActor"/> with the specified id,409 /// or null if no such actor exists.410 /// </summary>411 private TActor GetActorWithId<TActor>(ActorId id)412 where TActor : Actor =>413 id != null && this.ActorMap.TryGetValue(id, out Actor value) &&414 value is TActor actor ? actor : null;415 /// <summary>416 /// Returns the next available unique operation id.417 /// </summary>418 /// <returns>Value representing the next available unique operation id.</returns>419 private ulong GetNextOperationId() => this.Runtime.GetNextOperationId();420 /// <inheritdoc/>421 public bool RandomBoolean() => this.GetNondeterministicBooleanChoice(null, null);422 /// <summary>423 /// Returns a controlled nondeterministic boolean choice.424 /// </summary>425 internal virtual bool GetNondeterministicBooleanChoice(string callerName, string callerType) =>426 this.Runtime.GetNextNondeterministicBooleanChoice(callerName, callerType);427 /// <inheritdoc/>428 public int RandomInteger(int maxValue) => this.GetNondeterministicIntegerChoice(maxValue, null, null);429 /// <summary>430 /// Returns a controlled nondeterministic integer choice.431 /// </summary>432 internal virtual int GetNondeterministicIntegerChoice(int maxValue, string callerName, string callerType) =>433 this.Runtime.GetNextNondeterministicIntegerChoice(maxValue, callerName, callerType);434 /// <summary>435 /// Logs that the specified actor invoked an action.436 /// </summary>437 internal virtual void LogInvokedAction(Actor actor, MethodInfo action, string handlingStateName, string currentStateName)438 {439 if (this.Configuration.IsVerbose)440 {441 this.LogWriter.LogExecuteAction(actor.Id, handlingStateName, currentStateName, action.Name);442 }443 }444 /// <summary>445 /// Logs that the specified actor enqueued an <see cref="Event"/>.446 /// </summary>447 internal virtual void LogEnqueuedEvent(Actor actor, Event e, EventGroup eventGroup, EventInfo eventInfo)448 {449 if (this.Configuration.IsVerbose)450 {451 this.LogWriter.LogEnqueueEvent(actor.Id, e);452 }453 }454 /// <summary>455 /// Logs that the specified actor dequeued an <see cref="Event"/>.456 /// </summary>457 internal virtual void LogDequeuedEvent(Actor actor, Event e, EventInfo eventInfo, bool isFreshDequeue)458 {459 if (this.Configuration.IsVerbose)460 {461 string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : default;462 this.LogWriter.LogDequeueEvent(actor.Id, stateName, e);463 }464 }465 /// <summary>466 /// Logs that the specified actor dequeued the default <see cref="Event"/>.467 /// </summary>468 [MethodImpl(MethodImplOptions.AggressiveInlining)]469 internal virtual void LogDefaultEventDequeued(Actor actor)470 {471 }472 /// <summary>473 /// Logs that the specified actor raised an <see cref="Event"/>.474 /// </summary>475 internal virtual void LogRaisedEvent(Actor actor, Event e, EventGroup eventGroup, EventInfo eventInfo)476 {477 if (this.Configuration.IsVerbose)478 {479 string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : default;480 this.LogWriter.LogRaiseEvent(actor.Id, stateName, e);481 }482 }483 /// <summary>484 /// Logs that the specified actor is handling a raised <see cref="Event"/>.485 /// </summary>486 internal virtual void LogHandleRaisedEvent(Actor actor, Event e)487 {488 if (this.Configuration.IsVerbose)489 {490 string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : default;491 this.LogWriter.LogHandleRaisedEvent(actor.Id, stateName, e);492 }493 }494 /// <summary>495 /// Logs that the specified actor is handling a raised <see cref="HaltEvent"/>.496 /// </summary>497 internal virtual void LogHandleHaltEvent(Actor actor, int inboxSize)498 {499 if (this.Configuration.IsVerbose)500 {501 this.LogWriter.LogHalt(actor.Id, inboxSize);502 }503 }504 /// <summary>505 /// Logs that the specified actor called <see cref="Actor.ReceiveEventAsync(Type[])"/>506 /// or one of its overloaded methods.507 /// </summary>508 [MethodImpl(MethodImplOptions.AggressiveInlining)]509 internal virtual void LogReceiveCalled(Actor actor)510 {511 }512 /// <summary>513 /// Logs that the specified actor enqueued an event that it was waiting to receive.514 /// </summary>515 internal virtual void LogReceivedEvent(Actor actor, Event e, EventInfo eventInfo)516 {517 if (this.Configuration.IsVerbose)518 {519 string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : default;520 this.LogWriter.LogReceiveEvent(actor.Id, stateName, e, wasBlocked: true);521 }522 }523 /// <summary>524 /// Logs that the specified actor received an event without waiting because the event525 /// was already in the inbox when the actor invoked the receive statement.526 /// </summary>527 internal virtual void LogReceivedEventWithoutWaiting(Actor actor, Event e, EventInfo eventInfo)528 {529 if (this.Configuration.IsVerbose)530 {531 string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : default;532 this.LogWriter.LogReceiveEvent(actor.Id, stateName, e, wasBlocked: false);533 }534 }535 /// <summary>536 /// Logs that the specified actor is waiting to receive an event of one of the specified types.537 /// </summary>538 internal virtual void LogWaitEvent(Actor actor, IEnumerable<Type> eventTypes)539 {540 if (this.Configuration.IsVerbose)541 {542 string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : default;543 var eventWaitTypesArray = eventTypes.ToArray();544 if (eventWaitTypesArray.Length is 1)545 {546 this.LogWriter.LogWaitEvent(actor.Id, stateName, eventWaitTypesArray[0]);547 }548 else549 {550 this.LogWriter.LogWaitEvent(actor.Id, stateName, eventWaitTypesArray);551 }552 }553 }554 /// <summary>555 /// Logs that the event handler of the specified actor terminated.556 /// </summary>557 internal virtual void LogEventHandlerTerminated(Actor actor, DequeueStatus dequeueStatus)558 {559 if (this.Configuration.IsVerbose)560 {561 string stateName = actor is StateMachine stateMachine ? stateMachine.CurrentStateName : default;562 this.LogWriter.LogEventHandlerTerminated(actor.Id, stateName, dequeueStatus);563 }564 }565 /// <summary>566 /// Logs that the specified state machine entered a state.567 /// </summary>568 internal virtual void LogEnteredState(StateMachine stateMachine)569 {570 if (this.Configuration.IsVerbose)571 {572 this.LogWriter.LogStateTransition(stateMachine.Id, stateMachine.CurrentStateName, isEntry: true);573 }574 }575 /// <summary>576 /// Logs that the specified state machine exited a state.577 /// </summary>578 internal virtual void LogExitedState(StateMachine stateMachine)579 {580 if (this.Configuration.IsVerbose)581 {582 this.LogWriter.LogStateTransition(stateMachine.Id, stateMachine.CurrentStateName, isEntry: false);583 }584 }585 /// <summary>586 /// Logs that the specified state machine invoked pop.587 /// </summary>588 [MethodImpl(MethodImplOptions.AggressiveInlining)]589 internal virtual void LogPopState(StateMachine stateMachine)590 {591 }592 /// <summary>593 /// Logs that the specified state machine invoked an action.594 /// </summary>595 internal virtual void LogInvokedOnEntryAction(StateMachine stateMachine, MethodInfo action)596 {597 if (this.Configuration.IsVerbose)598 {599 this.LogWriter.LogExecuteAction(stateMachine.Id, stateMachine.CurrentStateName,600 stateMachine.CurrentStateName, action.Name);601 }602 }603 /// <summary>604 /// Logs that the specified state machine invoked an action.605 /// </summary>606 internal virtual void LogInvokedOnExitAction(StateMachine stateMachine, MethodInfo action)607 {608 if (this.Configuration.IsVerbose)609 {610 this.LogWriter.LogExecuteAction(stateMachine.Id, stateMachine.CurrentStateName,611 stateMachine.CurrentStateName, action.Name);612 }613 }614 /// <summary>615 /// Builds the coverage graph information, if any. This information is only available616 /// when <see cref="Configuration.IsActivityCoverageReported"/> is enabled.617 /// </summary>618 internal CoverageInfo BuildCoverageInfo()619 {620 var result = this.CoverageInfo;621 if (result != null)622 {623 var builder = this.LogWriter.GetLogsOfType<ActorRuntimeLogGraphBuilder>()624 .FirstOrDefault(builder => builder.CollapseInstances);625 if (builder != null)626 {627 result.CoverageGraph = builder.SnapshotGraph(false);628 }629 var eventCoverage = this.LogWriter.GetLogsOfType<ActorRuntimeLogEventCoverage>().FirstOrDefault();630 if (eventCoverage != null)631 {632 result.EventInfo = eventCoverage.EventCoverage;633 }634 }635 return result;636 }637 /// <summary>638 /// Returns the DGML graph of the current execution, if there is any.639 /// </summary>640 internal Graph GetExecutionGraph()641 {642 Graph result = null;643 var builder = this.LogWriter.GetLogsOfType<ActorRuntimeLogGraphBuilder>()644 .FirstOrDefault(builder => !builder.CollapseInstances);645 if (builder != null)646 {647 result = builder.SnapshotGraph(true);648 }649 return result;650 }651 /// <summary>652 /// Returns the program counter of the specified actor.653 /// </summary>654 [MethodImpl(MethodImplOptions.AggressiveInlining)]655 internal virtual int GetActorProgramCounter(ActorId actorId) => 0;656 /// <inheritdoc/>657 public void RegisterMonitor<T>()658 where T : Monitor =>659 this.Runtime.RegisterMonitor<T>();660 /// <inheritdoc/>661 public void Monitor<T>(Event e)662 where T : Monitor =>663 this.Runtime.Monitor<T>(e);664 /// <summary>665 /// Invokes the specified <see cref="Specifications.Monitor"/> with the specified <see cref="Event"/>.666 /// </summary>667 internal void InvokeMonitor(Type type, Event e, string senderName, string senderType, string senderStateName) =>668 this.Runtime.InvokeMonitor(type, e, senderName, senderType, senderStateName);669 /// <inheritdoc/>670 [MethodImpl(MethodImplOptions.AggressiveInlining)]671 public void Assert(bool predicate) => this.Runtime.Assert(predicate);672 /// <inheritdoc/>673 [MethodImpl(MethodImplOptions.AggressiveInlining)]674 public void Assert(bool predicate, string s, object arg0) => this.Runtime.Assert(predicate, s, arg0);675 /// <inheritdoc/>676 [MethodImpl(MethodImplOptions.AggressiveInlining)]677 public void Assert(bool predicate, string s, object arg0, object arg1) => this.Runtime.Assert(predicate, s, arg0, arg1);678 /// <inheritdoc/>679 [MethodImpl(MethodImplOptions.AggressiveInlining)]680 public void Assert(bool predicate, string s, object arg0, object arg1, object arg2) =>681 this.Runtime.Assert(predicate, s, arg0, arg1, arg2);682 /// <inheritdoc/>683 [MethodImpl(MethodImplOptions.AggressiveInlining)]684 public void Assert(bool predicate, string s, params object[] args) => this.Runtime.Assert(predicate, s, args);685 /// <summary>686 /// Asserts that the actor calling an actor method is also the actor that is currently executing.687 /// </summary>688 [MethodImpl(MethodImplOptions.AggressiveInlining)]689 internal virtual void AssertExpectedCallerActor(Actor caller, string calledAPI)690 {691 }692 /// <summary>693 /// Raises the <see cref="OnFailure"/> event with the specified <see cref="Exception"/>.694 /// </summary>695 internal void RaiseOnFailureEvent(Exception exception) => this.Runtime.RaiseOnFailureEvent(exception);696 /// <summary>697 /// Handle the specified dropped <see cref="Event"/>.698 /// </summary>699 internal void HandleDroppedEvent(Event e, ActorId id) => this.OnEventDropped?.Invoke(e, id);700 /// <summary>701 /// Throws an <see cref="AssertionFailureException"/> exception containing the specified exception.702 /// </summary>703#if !DEBUG704 [DebuggerHidden]705#endif706 internal void WrapAndThrowException(Exception exception, string s, params object[] args) =>707 this.Runtime.WrapAndThrowException(exception, s, args);708 /// <inheritdoc/>709 [Obsolete("Please set the Logger property directory instead of calling this method.")]710 public TextWriter SetLogger(TextWriter logger)711 {712 var result = this.LogWriter.SetLogger(new TextWriterLogger(logger));713 if (result != null)714 {715 return result.TextWriter;716 }717 return null;718 }719 /// <inheritdoc/>720 public void RegisterLog(IRuntimeLog log) => this.Runtime.RegisterLog(log);721 /// <inheritdoc/>722 public void RemoveLog(IRuntimeLog log) => this.Runtime.RemoveLog(log);723 /// <summary>724 /// Returns a task that completes once all actors reach quiescence.725 /// </summary>726 internal Task WaitUntilQuiescenceAsync()727 {728 lock (this.QuiescenceSyncObject)729 {730 if (this.EnabledActors.Count > 0)731 {732 this.IsActorQuiescenceAwaited = true;733 return this.QuiescenceCompletionSource.Task;734 }735 else736 {737 return Task.CompletedTask;738 }739 }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,...

Full Screen

Full Screen

OnActorEventHandlerStarted

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Threading.Tasks;4using Microsoft.Coyote;5using Microsoft.Coyote.Actors;6using Microsoft.Coyote.Actors.Timers;7using Microsoft.Coyote.Specifications;8{9 {10 public static void Main()11 {12 RunAsync().Wait();13 }14 public static async Task RunAsync()15 {16 var configuration = Configuration.Create();17 configuration.LivenessTemperatureThreshold = 0;18 configuration.SchedulingIterations = 10;19 configuration.SchedulingStrategy = SchedulingStrategy.DFS;20 configuration.UseRandomSchedulingSeed = true;21 configuration.EnableCycleDetection = true;22 configuration.EnableDataRaceDetection = true;23 configuration.EnableDeadlockDetection = true;24 configuration.EnableHotStateDetection = true;25 configuration.EnableLivenessChecking = true;26 configuration.EnableOperationInterleavings = true;27 configuration.EnablePhaseInterleavings = true;28 configuration.EnableRandomExecution = true;29 configuration.EnableStateGraph = true;30 configuration.EnableStateGraphScheduling = true;31 configuration.EnableStateGraphSchedulingWithFairness = true;32 configuration.EnableStateGraphSchedulingWithFairnessAndFairLiveness = true;33 configuration.EnableStateGraphSchedulingWithFairLiveness = true;34 configuration.EnableTestingIterations = true;35 configuration.EnableUnfairnessAnalysis = true;36 configuration.EnableVerboseTrace = true;37 configuration.MaxFairSchedulingSteps = 100;38 configuration.MaxInterleavings = 100;39 configuration.MaxLivenessTemperature = 100;40 configuration.MaxSchedulingSteps = 100;41 configuration.MaxUnfairSchedulingSteps = 100;42 configuration.MaxUnfairSchedulingStepsWhenFairnessIsBroken = 100;43 configuration.MaxUnfairSchedulingStepsWhenLivenessIsBroken = 100;44 configuration.RandomExecutionProbability = 0.5;45 configuration.SchedulingSteps = 10;46 configuration.TestingIterations = 10;47 configuration.UserAssemblies = new List<string>();48 configuration.UserAssemblies.Add("CoyoteApplication1");49 var runtime = RuntimeFactory.Create(configuration);50 runtime.OnActorEventHandlerStarted += OnActorEventHandlerStarted;51 runtime.OnActorEventHandlerCompleted += OnActorEventHandlerCompleted;52 runtime.OnActorCreated += OnActorCreated;53 runtime.OnActorEventIgnored += OnActorEventIgnored;

Full Screen

Full Screen

OnActorEventHandlerStarted

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Coyote;4using Microsoft.Coyote.Actors;5{6 {7 public static async Task Main(string[] args)8 {9 var runtime = RuntimeFactory.Create();10 var actor = runtime.CreateActor(typeof(MyActor));11 runtime.SendEvent(actor, new E());12 await runtime.WaitAsync(actor);13 }14 }15 {16 }17 {18 protected override async Task OnInitializeAsync(Event initialEvent)19 {20 await this.OnEventAsync<E>(async e =>21 {22 this.Assert(this.Id == this.Runtime.CurrentActorId, "Expected actor id '{0}' does not match current actor id '{1}'", this.Id, this.Runtime.CurrentActorId);23 this.Assert(this.Runtime.CurrentEvent == e, "Expected event '{0}' does not match current event '{1}'", e, this.Runtime.CurrentEvent);24 this.Assert(this.Runtime.CurrentActor == this, "Expected actor '{0}' does not match current actor '{1}'", this, this.Runtime.CurrentActor);25 });26 }27 }28}29using System;30using System.Threading.Tasks;31using Microsoft.Coyote;32using Microsoft.Coyote.Actors;33{34 {35 public static async Task Main(string[] args)36 {37 var runtime = RuntimeFactory.Create();38 var actor = runtime.CreateActor(typeof(MyActor));39 runtime.SendEvent(actor, new E());40 await runtime.WaitAsync(actor);41 }42 }43 {44 }45 {46 protected override async Task OnInitializeAsync(Event initialEvent)47 {48 await this.OnEventAsync<E>(async e =>49 {50 this.Assert(this.Id == this.Runtime.CurrentActorId, "

Full Screen

Full Screen

OnActorEventHandlerStarted

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Coyote;4using Microsoft.Coyote.Actors;5using Microsoft.Coyote.Specifications;6{7 {8 private static async Task Main(string[] args)9 {10 using (var runtime = RuntimeFactory.Create())11 {12 runtime.OnActorEventHandlerStarted += (sender, e) =>13 {14 Console.WriteLine($">> Actor {e.ActorId} is about to execute {e.ActionName}.");15 };16 var id = await runtime.CreateActorAsync(typeof(MyActor));17 await runtime.SendEventAsync(id, new MyEvent());18 await runtime.WaitAsync(id);19 }20 }21 }22 {23 }24 {25 [OnEventDoAction(typeof(MyEvent), nameof(HandleMyEvent))]26 {27 }28 private void HandleMyEvent()29 {30 }31 }32}33using System;34using System.Threading.Tasks;35using Microsoft.Coyote;36using Microsoft.Coyote.Actors;37using Microsoft.Coyote.Specifications;38{39 {40 private static async Task Main(string[] args)41 {42 using (var runtime = RuntimeFactory.Create())43 {44 runtime.OnActorEventHandlerCompleted += (sender, e) =>45 {46 Console.WriteLine($">> Actor {e.ActorId} has executed {e.ActionName}.");47 };48 var id = await runtime.CreateActorAsync(typeof(MyActor));49 await runtime.SendEventAsync(id, new MyEvent());50 await runtime.WaitAsync(id);51 }52 }53 }54 {55 }56 {

Full Screen

Full Screen

OnActorEventHandlerStarted

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Coyote;4using Microsoft.Coyote.Actors;5using Microsoft.Coyote.Specifications;6{7 {8 public static void Main(string[] args)9 {10 Runtime.Run(async () =>11 {12 var runtime = RuntimeFactory.Create();13 var actor = runtime.CreateActor(typeof(MonitoredActor));14 runtime.SendEvent(actor, new E());15 });16 }17 }18 {19 }20 {21 protected override Task OnInitializeAsync(Event initialEvent)22 {23 this.OnActorEventHandlerStarted += this.OnActorEventHandlerStartedHandler;24 return Task.CompletedTask;25 }26 private void OnActorEventHandlerStartedHandler(object sender, ActorEventArgs e)27 {28 Console.WriteLine("Actor event handler started");29 }30 protected override Task OnEventAsync(Event e)31 {32 return Task.CompletedTask;33 }34 }35}36using System;37using System.Threading.Tasks;38using Microsoft.Coyote;39using Microsoft.Coyote.Actors;40using Microsoft.Coyote.Specifications;41{42 {43 public static void Main(string[] args)44 {45 Runtime.Run(async () =>46 {47 var runtime = RuntimeFactory.Create();48 var actor = runtime.CreateActor(typeof(MonitoredActor));49 runtime.SendEvent(actor, new E());50 });51 }52 }53 {54 }55 {56 protected override Task OnInitializeAsync(Event initialEvent)57 {58 this.OnActorEventHandlerCompleted += this.OnActorEventHandlerCompletedHandler;59 return Task.CompletedTask;60 }61 private void OnActorEventHandlerCompletedHandler(object sender, ActorEventArgs e)62 {63 Console.WriteLine("Actor event handler completed");64 }65 protected override Task OnEventAsync(Event e)

Full Screen

Full Screen

OnActorEventHandlerStarted

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Actors;2using System;3{4 {5 static void Main(string[] args)6 {7 var runtime = RuntimeFactory.Create();8 runtime.OnActorEventHandlerStarted += (sender, e) =>9 {10 Console.WriteLine($"Actor {e.ActorId} started handling event {e.Event.GetType().Name}.");11 };12 runtime.CreateActor(typeof(MyActor));13 runtime.SendEvent(new MyEvent());14 Console.ReadLine();15 }16 }17 {18 protected override void OnEvent(Event e)19 {20 if (e is MyEvent)21 {22 Console.WriteLine("MyEvent received!");23 }24 }25 }26 class MyEvent : Event { }27}28using Microsoft.Coyote.Actors;29using System;30{31 {32 static void Main(string[] args)33 {34 var runtime = RuntimeFactory.Create();35 runtime.OnActorEventHandlerCompleted += (sender, e) =>36 {37 Console.WriteLine($"Actor {e.ActorId} completed handling event {e.Event.GetType().Name}.");38 };39 runtime.CreateActor(typeof(MyActor));40 runtime.SendEvent(new MyEvent());41 Console.ReadLine();42 }43 }44 {45 protected override void OnEvent(Event e)46 {47 if (e is MyEvent)48 {49 Console.WriteLine("MyEvent received!");50 }51 }52 }53 class MyEvent : Event { }54}55using Microsoft.Coyote.Actors;56using System;57{58 {59 static void Main(string[] args)60 {61 var runtime = RuntimeFactory.Create();62 runtime.OnActorEventHandlerFailed += (sender, e) =>63 {64 Console.WriteLine($"Actor {e.ActorId} failed to handle event {e.Event.GetType().Name}.");65 };66 runtime.CreateActor(typeof(MyActor));67 runtime.SendEvent(new MyEvent());68 Console.ReadLine();69 }70 }71 {72 protected override void OnEvent(Event e)73 {74 if (e is

Full Screen

Full Screen

OnActorEventHandlerStarted

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Actors;2using Microsoft.Coyote.Actors.Timers;3using Microsoft.Coyote.Specifications;4using System;5using System.Threading.Tasks;6{7 {8 static void Main(string[] args)9 {10 Console.WriteLine("Hello World!");11 var runtime = RuntimeFactory.Create();12 runtime.CreateActor(typeof(MyActor));13 runtime.Run();14 }15 }16 {17 protected override Task OnInitializeAsync(Event initialEvent)18 {19 this.OnActorEventHandlerStarted += MyActor_OnActorEventHandlerStarted;20 this.SendEvent(this.Id, new MyEvent());21 return Task.CompletedTask;22 }23 private void MyActor_OnActorEventHandlerStarted(object sender, ActorEventArgs e)24 {25 Console.WriteLine("Actor event handler started");26 }27 private Task MyEventHandler(MyEvent e)28 {29 Console.WriteLine("MyEventHandler");30 return Task.CompletedTask;31 }32 [OnEventDoAction(typeof(MyEvent), nameof(MyEventHandler))]33 {34 }35 }36}37using Microsoft.Coyote.Actors;38using Microsoft.Coyote.Actors.Timers;39using Microsoft.Coyote.Specifications;40using System;41using System.Threading.Tasks;42{43 {44 static void Main(string[] args)45 {46 Console.WriteLine("Hello World!");47 var runtime = RuntimeFactory.Create();48 runtime.CreateActor(typeof(MyActor));49 runtime.Run();50 }51 }52 {53 protected override Task OnInitializeAsync(Event initialEvent)54 {55 this.OnActorEventHandlerCompleted += MyActor_OnActorEventHandlerCompleted;56 this.SendEvent(this.Id, new MyEvent());57 return Task.CompletedTask;58 }59 private void MyActor_OnActorEventHandlerCompleted(object sender, ActorEventArgs e)60 {61 Console.WriteLine("Actor event handler completed");62 }63 private Task MyEventHandler(MyEvent e)64 {65 Console.WriteLine("MyEventHandler");66 return Task.CompletedTask;67 }

Full Screen

Full Screen

OnActorEventHandlerStarted

Using AI Code Generation

copy

Full Screen

1{2 {3 static void Main(string[] args)4 {5 var runtime = RuntimeFactory.Create();6 runtime.OnActorEventHandlerFailed += (sender, e) =>7 {8 Console.WriteLine($"Actor {e.ActorId} failed to handle event {e.Event.GetType().Name}.");9 };10 runtime.CreateActor(typeof(MyActor));11 runtime.SendEvent(new MyEvent());12 Console.ReadLine();13 }14 }15 {16 protected override void OnEvent(Event e)17 {18 if (e is

Full Screen

Full Screen

OnActorEventHandlerStarted

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Actors;2using Microsoft.Coyote.Actors.Timers;3using Microsoft.Coyote.Specifications;4using System;5using System.Threading.Tasks;6{7 {8 static void Main(string[] args)9 {10 Console.WriteLine("Hello World!");11 var runtime = RuntimeFactory.Create();12 runtime.CreateActor(typeof(MyActor));13 runtime.Run();14 }15 }16 {17 protected override Task OnInitializeAsync(Event initialEvent)18 {19 this.OnActorEventHandlerStarted += MyActor_OnActorEventHandlerStarted;20 this.SendEvent(this.Id, new MyEvent());21 return Task.CompletedTask;22 }23 private void MyActor_OnActorEventHandlerStarted(object sender, ActorEventArgs e)24 {25 Console.WriteLine("Actor event handler started");26 }27 private Task MyEventHandler(MyEvent e)28 {29 Console.WriteLine("MyEventHandler");30 return Task.CompletedTask;31 }32 [OnEventDoAction(typeof(MyEvent), nameof(MyEventHandler))]33 {34 }35 }36}37using Microsoft.Coyote.Actors;38using Microsoft.Coyote.Actors.Timers;39using Microsoft.Coyote.Specifications;40using System;41using System.Threading.Tasks;42{43 {44 static void Main(string[] args)45 {46 Console.WriteLine("Hello World!");47 var runtime = RuntimeFactory.Create();48 runtime.CreateActor(typeof(MyActor));49 runtime.Run();50 }51 }52 {53 protected override Task OnInitializeAsync(Event initialEvent)54 {55 this.OnActorEventHandlerCompleted += MyActor_OnActorEventHandlerCompleted;56 this.SendEvent(this.Id, new MyEvent());57 return Task.CompletedTask;58 }59 private void MyActor_OnActorEventHandlerCompleted(object sender, ActorEventArgs e)60 {61 Console.WriteLine("Actor event handler completed");62 }63 private Task MyEventHandler(MyEvent e)64 {65 Console.WriteLine("MyEventHandler");66 return Task.CompletedTask;67 }

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful