How to use CachedDelegate class of Microsoft.Coyote.Specifications package

Best Coyote code snippet using Microsoft.Coyote.Specifications.CachedDelegate

Monitor.cs

Source:Monitor.cs Github

copy

Full Screen

...65 internal Dictionary<Type, EventHandlerDeclaration> EventHandlers;66 /// <summary>67 /// Map from action names to cached action delegates.68 /// </summary>69 private readonly Dictionary<string, CachedDelegate> ActionMap;70 /// <summary>71 /// Set of currently ignored event types.72 /// </summary>73 private HashSet<Type> IgnoredEvents;74 /// <summary>75 /// A counter that increases in each step of the execution, as long as the monitor76 /// remains in a hot state. If the temperature reaches the specified limit, then77 /// a potential liveness bug has been found.78 /// </summary>79 private int LivenessTemperature;80 /// <summary>81 /// Gets the name of this monitor.82 /// </summary>83 internal string Name => this.GetType().FullName;84 /// <summary>85 /// Responsible for logging.86 /// </summary>87 private LogWriter LogWriter;88 /// <summary>89 /// The logger installed to the runtime.90 /// </summary>91 /// <remarks>92 /// See <see href="/coyote/concepts/actors/logging" >Logging</see> for more information.93 /// </remarks>94 protected ILogger Logger => this.LogWriter.Logger;95 /// <summary>96 /// Gets the current state.97 /// </summary>98 protected internal Type CurrentState99 {100 get => this.ActiveState?.GetType();101 }102 /// <summary>103 /// Gets the current state name.104 /// </summary>105 internal string CurrentStateName106 {107 get => NameResolver.GetQualifiedStateName(this.CurrentState);108 }109 /// <summary>110 /// Gets the current state name with temperature.111 /// </summary>112 private string CurrentStateNameWithTemperature113 {114 get115 {116 return this.CurrentStateName +117 (this.IsInHotState() ? "[hot]" :118 this.IsInColdState() ? "[cold]" :119 string.Empty);120 }121 }122 /// <summary>123 /// User-defined hashed state of the monitor. Override to improve the124 /// accuracy of stateful techniques during testing.125 /// </summary>126 protected virtual int HashedState => 0;127 /// <summary>128 /// A pending transition object that has not been returned from ExecuteAction yet.129 /// </summary>130 private Transition PendingTransition;131 /// <summary>132 /// Initializes a new instance of the <see cref="Monitor"/> class.133 /// </summary>134 protected Monitor()135 : base()136 {137 this.ActionMap = new Dictionary<string, CachedDelegate>();138 this.LivenessTemperature = 0;139 }140 /// <summary>141 /// Initializes this monitor.142 /// </summary>143 internal void Initialize(Configuration configuration, CoyoteRuntime runtime, LogWriter logWriter)144 {145 this.Configuration = configuration;146 this.Runtime = runtime;147 this.LogWriter = logWriter;148 }149 /// <summary>150 /// Raises the specified <see cref="Event"/> at the end of the current action.151 /// </summary>152 /// <remarks>153 /// This event is not handled until the action that calls this method returns control back154 /// to the Coyote runtime. It is handled before any other events are dequeued from the inbox.155 /// Only one of the following can be called per action:156 /// <see cref="RaiseEvent"/>, <see cref="RaiseGotoStateEvent{T}"/>.157 /// An Assert is raised if you accidentally try and do two of these operations in a single action.158 /// </remarks>159 /// <param name="e">The event to raise.</param>160 protected void RaiseEvent(Event e)161 {162 this.Assert(e != null, "{0} is raising a null event.", this.Name);163 this.CheckDanglingTransition();164 this.PendingTransition = new Transition(Transition.Type.Raise, default, e);165 }166 /// <summary>167 /// Raise a special event that performs a goto state operation at the end of the current action.168 /// </summary>169 /// <remarks>170 /// Goto state pops the current <see cref="State"/> and pushes the specified <see cref="State"/> on the active state stack.171 ///172 /// This is shorthand for the following code:173 /// <code>174 /// class Event E { }175 /// [OnEventGotoState(typeof(E), typeof(S))]176 /// this.RaiseEvent(new E());177 /// </code>178 /// This event is not handled until the action that calls this method returns control back179 /// to the Coyote runtime. It is handled before any other events are dequeued from the inbox.180 /// Only one of the following can be called per action:181 /// <see cref="RaiseEvent"/>, <see cref="RaiseGotoStateEvent{T}"/>.182 /// An Assert is raised if you accidentally try and do two of these operations in a single action.183 /// </remarks>184 /// <typeparam name="TState">Type of the state.</typeparam>185 protected void RaiseGotoStateEvent<TState>()186 where TState : State =>187 this.RaiseGotoStateEvent(typeof(TState));188 /// <summary>189 /// Raise a special event that performs a goto state operation at the end of the current action.190 /// </summary>191 /// <remarks>192 /// Goto state pops the current <see cref="State"/> and pushes the specified <see cref="State"/> on the active state stack.193 ///194 /// This is shorthand for the following code:195 /// <code>196 /// class Event E { }197 /// [OnEventGotoState(typeof(E), typeof(S))]198 /// this.RaiseEvent(new E());199 /// </code>200 /// This event is not handled until the action that calls this method returns control back201 /// to the Coyote runtime. It is handled before any other events are dequeued from the inbox.202 /// Only one of the following can be called per action:203 /// <see cref="RaiseEvent"/>, <see cref="RaiseGotoStateEvent{T}"/>.204 /// An Assert is raised if you accidentally try and do two of these operations in a single action.205 /// </remarks>206 /// <param name="state">Type of the state.</param>207 protected void RaiseGotoStateEvent(Type state)208 {209 // If the state is not a state of the monitor, then report an error and exit.210 this.Assert(StateTypeMap[this.GetType()].Any(val => val.DeclaringType.Equals(state.DeclaringType) && val.Name.Equals(state.Name)),211 "{0} is trying to transition to non-existing state '{1}'.", this.Name, state.Name);212 this.CheckDanglingTransition();213 this.PendingTransition = new Transition(Transition.Type.Goto, state, default);214 }215 /// <summary>216 /// Checks if the assertion holds, and if not, throws an <see cref="AssertionFailureException"/> exception.217 /// </summary>218 protected void Assert(bool predicate)219 {220 if (!predicate)221 {222 this.LogMonitorError(this);223 this.Runtime.Assert(false);224 }225 }226 /// <summary>227 /// Checks if the assertion holds, and if not, throws an <see cref="AssertionFailureException"/> exception.228 /// </summary>229 protected void Assert(bool predicate, string s, object arg0)230 {231 if (!predicate)232 {233 this.LogMonitorError(this);234 this.Runtime.Assert(false, s, arg0);235 }236 }237 /// <summary>238 /// Checks if the assertion holds, and if not, throws an <see cref="AssertionFailureException"/> exception.239 /// </summary>240 protected void Assert(bool predicate, string s, object arg0, object arg1)241 {242 if (!predicate)243 {244 this.LogMonitorError(this);245 this.Runtime.Assert(false, s, arg0, arg1);246 }247 }248 /// <summary>249 /// Checks if the assertion holds, and if not, throws an <see cref="AssertionFailureException"/> exception.250 /// </summary>251 protected void Assert(bool predicate, string s, object arg0, object arg1, object arg2)252 {253 if (!predicate)254 {255 this.LogMonitorError(this);256 this.Runtime.Assert(false, s, arg0, arg1, arg2);257 }258 }259 /// <summary>260 /// Checks if the assertion holds, and if not, throws an <see cref="AssertionFailureException"/> exception.261 /// </summary>262 protected void Assert(bool predicate, string s, params object[] args)263 {264 if (!predicate)265 {266 this.LogMonitorError(this);267 this.Runtime.Assert(false, s, args);268 }269 }270 /// <summary>271 /// Notifies the monitor to handle the received event.272 /// </summary>273 internal void MonitorEvent(Event e, string senderName, string senderType, string senderState)274 {275 this.LogWriter.LogMonitorProcessEvent(this.Name, this.CurrentStateName, senderName, senderType, senderState, e);276 this.HandleEvent(e);277 }278 /// <summary>279 /// Handles the given event.280 /// </summary>281 private void HandleEvent(Event e)282 {283 // Do not process an ignored event.284 if (this.IsEventIgnoredInCurrentState(e))285 {286 return;287 }288 while (true)289 {290 if (this.ActiveState is null)291 {292 // If the event cannot be handled, then report an error and exit.293 this.Assert(false, "{0} received event '{1}' that cannot be handled.",294 this.Name, e.GetType().FullName);295 }296 // If current state cannot handle the event then null the state.297 if (!this.CanHandleEvent(e.GetType()))298 {299 this.LogExitedState(this);300 this.ActiveState = null;301 continue;302 }303 if (e.GetType() == typeof(GotoStateEvent))304 {305 // Checks if the event is a goto state event.306 Type targetState = (e as GotoStateEvent).State;307 this.GotoState(targetState, null, e);308 }309 else if (this.EventHandlers.ContainsKey(e.GetType()))310 {311 // Checks if the event can trigger an action.312 var handler = this.EventHandlers[e.GetType()];313 if (handler is ActionEventHandlerDeclaration action)314 {315 this.Do(action.Name, e);316 }317 else if (handler is GotoStateTransition transition)318 {319 this.GotoState(transition.TargetState, transition.Lambda, e);320 }321 }322 else if (this.EventHandlers.ContainsKey(typeof(WildCardEvent)))323 {324 // Checks if the event can trigger an action.325 var handler = this.EventHandlers[typeof(WildCardEvent)];326 if (handler is ActionEventHandlerDeclaration action)327 {328 this.Do(action.Name, e);329 }330 else if (handler is GotoStateTransition transition)331 {332 this.GotoState(transition.TargetState, transition.Lambda, e);333 }334 }335 break;336 }337 }338 /// <summary>339 /// Checks if the specified event is ignored in the current monitor state.340 /// </summary>341 private bool IsEventIgnoredInCurrentState(Event e)342 {343 if (this.IgnoredEvents.Contains(e.GetType()) ||344 this.IgnoredEvents.Contains(typeof(WildCardEvent)))345 {346 return true;347 }348 return false;349 }350 /// <summary>351 /// Invokes an action.352 /// </summary>353#if !DEBUG354 [System.Diagnostics.DebuggerStepThrough]355#endif356 private void Do(string actionName, Event e)357 {358 CachedDelegate cachedAction = this.ActionMap[actionName];359 this.LogInvokedAction(this, cachedAction.MethodInfo, this.CurrentStateNameWithTemperature);360 this.ExecuteAction(cachedAction, e);361 this.ApplyEventHandlerTransition(this.PendingTransition);362 }363 /// <summary>364 /// Executes the on entry function of the current state.365 /// </summary>366#if !DEBUG367 [System.Diagnostics.DebuggerStepThrough]368#endif369 private void ExecuteCurrentStateOnEntry(Event e)370 {371 this.LogEnteredState(this);372 CachedDelegate entryAction = null;373 if (this.ActiveState.EntryAction != null)374 {375 entryAction = this.ActionMap[this.ActiveState.EntryAction];376 }377 // Invokes the entry action of the new state,378 // if there is one available.379 if (entryAction != null)380 {381 this.ExecuteAction(entryAction, e);382 this.ApplyEventHandlerTransition(this.PendingTransition);383 }384 }385 /// <summary>386 /// Executes the on exit function of the current state.387 /// </summary>388#if !DEBUG389 [System.Diagnostics.DebuggerStepThrough]390#endif391 private void ExecuteCurrentStateOnExit(string eventHandlerExitActionName, Event e)392 {393 this.LogExitedState(this);394 CachedDelegate exitAction = null;395 if (this.ActiveState.ExitAction != null)396 {397 exitAction = this.ActionMap[this.ActiveState.ExitAction];398 }399 // Invokes the exit action of the current state,400 // if there is one available.401 if (exitAction != null)402 {403 this.ExecuteAction(exitAction, e);404 Transition transition = this.PendingTransition;405 this.Assert(transition.TypeValue is Transition.Type.None,406 "{0} has performed a '{1}' transition from an OnExit action.",407 this.Name, transition.TypeValue);408 this.ApplyEventHandlerTransition(transition);409 }410 // Invokes the exit action of the event handler,411 // if there is one available.412 if (eventHandlerExitActionName != null)413 {414 CachedDelegate eventHandlerExitAction = this.ActionMap[eventHandlerExitActionName];415 this.ExecuteAction(eventHandlerExitAction, e);416 Transition transition = this.PendingTransition;417 this.Assert(transition.TypeValue is Transition.Type.None,418 "{0} has performed a '{1}' transition from an OnExit action.",419 this.Name, transition.TypeValue);420 this.ApplyEventHandlerTransition(transition);421 }422 }423 /// <summary>424 /// Executes the specified action.425 /// </summary>426#if !DEBUG427 [System.Diagnostics.DebuggerStepThrough]428#endif429 private void ExecuteAction(CachedDelegate cachedAction, Event e)430 {431 try432 {433 if (cachedAction.Handler is Action<Event> actionWithEvent)434 {435 actionWithEvent(e);436 }437 else if (cachedAction.Handler is Action action)438 {439 action();440 }441 }442 catch (Exception ex)443 {444 Exception innerException = ex;445 while (innerException is TargetInvocationException)446 {447 innerException = innerException.InnerException;448 }449 if (innerException is AggregateException)450 {451 innerException = innerException.InnerException;452 }453 if (innerException.GetBaseException() is System.Threading.ThreadInterruptedException threadEx)454 {455 ExceptionDispatchInfo.Capture(threadEx).Throw();456 }457 else458 {459 // Reports the unhandled exception.460 this.ReportUnhandledException(innerException, cachedAction.MethodInfo.Name);461 }462 }463 }464 /// <summary>465 /// Applies the specified event handler transition.466 /// </summary>467 private void ApplyEventHandlerTransition(Transition transition)468 {469 if (transition.TypeValue != this.PendingTransition.TypeValue && this.PendingTransition.TypeValue != Transition.Type.None)470 {471 this.CheckDanglingTransition();472 }473 else if (transition.TypeValue is Transition.Type.Raise)474 {475 this.PendingTransition = default;476 var e = transition.Event;477 this.LogRaisedEvent(this, e);478 this.HandleEvent(e);479 }480 else if (transition.TypeValue is Transition.Type.Goto)481 {482 this.PendingTransition = default;483 var e = new GotoStateEvent(transition.State);484 this.LogRaisedEvent(this, e);485 this.HandleEvent(e);486 }487 else488 {489 this.PendingTransition = default;490 }491 }492 /// <summary>493 /// Notifies that a Transition was created but not returned to the Monitor.494 /// </summary>495 private void CheckDanglingTransition()496 {497 var transition = this.PendingTransition;498 this.PendingTransition = default;499 if (transition.TypeValue != Transition.Type.None)500 {501 string prefix = string.Format("{0} Transition created by {1} in state {2} was not processed",502 transition.TypeValue, this.Name, this.CurrentStateName);503 string suffix = null;504 if (transition.State != null && transition.Event != null)505 {506 suffix = string.Format(", state {0}, event {1}.", transition.State, transition.Event);507 }508 else if (transition.State != null)509 {510 suffix = string.Format(", state {0}.", transition.State);511 }512 else if (transition.Event != null)513 {514 suffix = string.Format(", event {0}.", transition.Event);515 }516 this.Assert(false, prefix + suffix);517 }518 }519 /// <summary>520 /// Performs a goto transition to the given state.521 /// </summary>522 private void GotoState(Type s, string onExitActionName, Event e)523 {524 // The monitor performs the on exit statements of the current state.525 this.ExecuteCurrentStateOnExit(onExitActionName, e);526 var nextState = StateMap[this.GetType()].First(val => val.GetType().Equals(s));527 this.ConfigureStateTransitions(nextState);528 // The monitor transitions to the new state.529 this.ActiveState = nextState;530 if (nextState.IsCold)531 {532 this.LivenessTemperature = 0;533 }534 // The monitor performs the on entry statements of the new state.535 this.ExecuteCurrentStateOnEntry(e);536 }537 /// <summary>538 /// Checks if the state can handle the given event type. An event539 /// can be handled if it is deferred, or leads to a transition or540 /// action binding.541 /// </summary>542 private bool CanHandleEvent(Type e)543 {544 if (this.EventHandlers.ContainsKey(e) ||545 this.EventHandlers.ContainsKey(typeof(WildCardEvent)) ||546 e == typeof(GotoStateEvent))547 {548 return true;549 }550 return false;551 }552 /// <summary>553 /// Checks the liveness temperature of the monitor and report a potential liveness bug if the554 /// the value exceeded the specified threshold.555 /// </summary>556 /// <remarks>557 /// This method only works if this is a liveness monitor.558 /// </remarks>559 internal bool IsLivenessThresholdExceeded(int threshold)560 {561 if (this.ActiveState.IsHot && threshold > 0)562 {563 this.LivenessTemperature++;564 if (this.LivenessTemperature > threshold)565 {566 this.LogMonitorError(this);567 return true;568 }569 }570 return false;571 }572 /// <summary>573 /// Returns true if the monitor is in a hot state.574 /// </summary>575 private bool IsInHotState() => this.ActiveState?.IsHot ?? false;576 /// <summary>577 /// Returns true if the monitor is in a hot state. Also outputs578 /// the name of the current state.579 /// </summary>580 internal bool IsInHotState(out string stateName)581 {582 stateName = this.CurrentStateName;583 return this.IsInHotState();584 }585 /// <summary>586 /// Returns true if the monitor is in a cold state.587 /// </summary>588 private bool IsInColdState() => this.ActiveState?.IsCold ?? false;589 /// <summary>590 /// Returns a nullable boolean indicating liveness temperature: true for hot, false for cold, else null.591 /// </summary>592 internal bool? GetHotState() => this.IsInHotState() ? true : this.IsInColdState() ? (bool?)false : null;593 /// <summary>594 /// Returns the hashed state of this monitor.595 /// </summary>596 internal int GetHashedState()597 {598 unchecked599 {600 var hash = 19;601 hash = (hash * 31) + this.GetType().GetHashCode();602 hash = (hash * 31) + this.CurrentState.GetHashCode();603 if (this.HashedState != 0)604 {605 // Adds the user-defined hashed state.606 hash = (hash * 31) + this.HashedState;607 }608 return hash;609 }610 }611 /// <summary>612 /// Returns a string that represents the current monitor.613 /// </summary>614 public override string ToString() => this.Name;615 /// <summary>616 /// Transitions to the start state, and executes the617 /// entry action, if there is any.618 /// </summary>619 internal void GotoStartState()620 {621 this.LogWriter.LogCreateMonitor(this.Name);622 if (this.Runtime.SchedulingPolicy is SchedulingPolicy.Interleaving623 && this.Configuration.IsActivityCoverageReported)624 {625 this.ReportActivityCoverage(this.Runtime.DefaultActorExecutionContext.CoverageInfo);626 }627 this.ExecuteCurrentStateOnEntry(DefaultEvent.Instance);628 }629 /// <summary>630 /// Initializes information about the states of the monitor.631 /// </summary>632 internal void InitializeStateInformation()633 {634 Type monitorType = this.GetType();635 // If this type has not already been setup in the MonitorActionMap, then we need to try and grab the ActionCacheLock636 // for this type. First make sure we have one and only one lockable object for this type.637 object syncObject = ActionCacheLocks.GetOrAdd(monitorType, _ => new object());638 // Locking this syncObject ensures only one thread enters the initialization code to update639 // the ActionCache for this specific Actor type.640 lock (syncObject)641 {642 if (MonitorActionMap.ContainsKey(monitorType))643 {644 // Note: even if we won the GetOrAdd, there is a tiny window of opportunity for another thread645 // to slip in and lock the syncObject before us, so we have to check the ActionCache again646 // here just in case.647 }648 else649 {650 // Caches the actions declarations for this monitor type.651 if (MonitorActionMap.TryAdd(monitorType, new Dictionary<string, MethodInfo>()))652 {653 // Caches the available state types for this monitor type.654 if (StateTypeMap.TryAdd(monitorType, new HashSet<Type>()))655 {656 Type baseType = monitorType;657 while (baseType != typeof(Monitor))658 {659 foreach (var s in baseType.GetNestedTypes(BindingFlags.Instance |660 BindingFlags.NonPublic | BindingFlags.Public |661 BindingFlags.DeclaredOnly))662 {663 this.ExtractStateTypes(s);664 }665 baseType = baseType.BaseType;666 }667 }668 // Caches the available state instances for this monitor type.669 if (StateMap.TryAdd(monitorType, new HashSet<State>()))670 {671 foreach (var type in StateTypeMap[monitorType])672 {673 Type stateType = type;674 if (type.IsAbstract)675 {676 continue;677 }678 if (type.IsGenericType)679 {680 // If the state type is generic (only possible if inherited by a681 // generic monitor declaration), then iterate through the base682 // monitor classes to identify the runtime generic type, and use683 // it to instantiate the runtime state type. This type can be684 // then used to create the state constructor.685 Type declaringType = this.GetType();686 while (!declaringType.IsGenericType ||687 !type.DeclaringType.FullName.Equals(declaringType.FullName.Substring(688 0, declaringType.FullName.IndexOf('['))))689 {690 declaringType = declaringType.BaseType;691 }692 if (declaringType.IsGenericType)693 {694 stateType = type.MakeGenericType(declaringType.GetGenericArguments());695 }696 }697 ConstructorInfo constructor = stateType.GetConstructor(Type.EmptyTypes);698 var lambda = Expression.Lambda<Func<State>>(Expression.New(constructor)).Compile();699 State state = lambda();700 state.InitializeState();701 this.Assert(702 (state.IsCold && !state.IsHot) ||703 (!state.IsCold && state.IsHot) ||704 (!state.IsCold && !state.IsHot),705 "State '{0}' of {1} cannot be both cold and hot.", type.FullName, this.Name);706 StateMap[monitorType].Add(state);707 }708 }709 foreach (var state in StateMap[monitorType])710 {711 if (state.EntryAction != null &&712 !MonitorActionMap[monitorType].ContainsKey(state.EntryAction))713 {714 MonitorActionMap[monitorType].Add(715 state.EntryAction,716 this.GetActionWithName(state.EntryAction));717 }718 if (state.ExitAction != null &&719 !MonitorActionMap[monitorType].ContainsKey(state.ExitAction))720 {721 MonitorActionMap[monitorType].Add(722 state.ExitAction,723 this.GetActionWithName(state.ExitAction));724 }725 foreach (var handler in state.EventHandlers.Values)726 {727 if (handler is ActionEventHandlerDeclaration action)728 {729 if (!MonitorActionMap[monitorType].ContainsKey(action.Name))730 {731 MonitorActionMap[monitorType].Add(732 action.Name,733 this.GetActionWithName(action.Name));734 }735 }736 else if (handler is GotoStateTransition transition)737 {738 if (transition.Lambda != null &&739 !MonitorActionMap[monitorType].ContainsKey(transition.Lambda))740 {741 MonitorActionMap[monitorType].Add(742 transition.Lambda,743 this.GetActionWithName(transition.Lambda));744 }745 }746 }747 }748 }749 }750 }751 // Populates the map of actions for this monitor instance.752 foreach (var kvp in MonitorActionMap[monitorType])753 {754 this.ActionMap.Add(kvp.Key, new CachedDelegate(kvp.Value, this));755 }756 var initialStates = StateMap[monitorType].Where(state => state.IsStart).ToList();757 this.Assert(initialStates.Count != 0, "{0} must declare a start state.", this.Name);758 this.Assert(initialStates.Count is 1, "{0} can not declare more than one start states.", this.Name);759 this.ConfigureStateTransitions(initialStates.Single());760 this.ActiveState = initialStates.Single();761 this.AssertStateValidity();762 }763 /// <summary>764 /// Processes a type, looking for monitor states.765 /// </summary>766 private void ExtractStateTypes(Type type)767 {768 Stack<Type> stack = new Stack<Type>();...

Full Screen

Full Screen

CachedDelegate.cs

Source:CachedDelegate.cs Github

copy

Full Screen

...6{7 /// <summary>8 /// A monitor delegate that has been cached to optimize performance of invocations.9 /// </summary>10 internal class CachedDelegate11 {12 internal readonly MethodInfo MethodInfo;13 internal readonly Delegate Handler;14 internal CachedDelegate(MethodInfo method, object caller)15 {16 ParameterInfo[] parameters = method.GetParameters();17 if (parameters.Length is 1 && method.ReturnType == typeof(void))18 {19 this.Handler = Delegate.CreateDelegate(typeof(Action<Event>), caller, method);20 }21 else if (method.ReturnType == typeof(void))22 {23 this.Handler = Delegate.CreateDelegate(typeof(Action), caller, method);24 }25 else if (parameters.Length is 1 && method.ReturnType == typeof(Monitor.Transition))26 {27 this.Handler = Delegate.CreateDelegate(typeof(Func<Event, Monitor.Transition>), caller, method);28 }...

Full Screen

Full Screen

CachedDelegate

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Microsoft.Coyote.Specifications;7using Microsoft.Coyote.Tasks;8{9 {10 public static void Main(string[] args)11 {12 CachedDelegate<int> cachedDelegate = new CachedDelegate<int>(() => 1);13 Task<int> task = new Task<int>(() => cachedDelegate.Invoke());14 task.Start();15 task.Wait();16 Console.WriteLine($"Result: {task.Result}");17 }18 }19}20using System;21using System.Collections.Generic;22using System.Linq;23using System.Text;24using System.Threading.Tasks;25using Microsoft.Coyote.Specifications;26using Microsoft.Coyote.Tasks;27{28 {29 public static void Main(string[] args)30 {31 CachedDelegate<int> cachedDelegate = new CachedDelegate<int>(() => 1);32 Task<int> task = new Task<int>(() => cachedDelegate.Invoke());33 task.Start();34 task.Wait();35 Console.WriteLine($"Result: {task.Result}");36 }37 }38}39using System;40using System.Collections.Generic;41using System.Linq;42using System.Text;43using System.Threading.Tasks;44using Microsoft.Coyote.Specifications;45using Microsoft.Coyote.Tasks;46{47 {48 public static void Main(string[] args)49 {50 CachedDelegate<int> cachedDelegate = new CachedDelegate<int>(() => 1);51 Task<int> task = new Task<int>(() => cachedDelegate.Invoke());52 task.Start();53 task.Wait();54 Console.WriteLine($"Result: {task.Result}");55 }56 }57}58using System;59using System.Collections.Generic;60using System.Linq;61using System.Text;62using System.Threading.Tasks;63using Microsoft.Coyote.Specifications;64using Microsoft.Coyote.Tasks;65{66 {67 public static void Main(string[] args)68 {

Full Screen

Full Screen

CachedDelegate

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Coyote;4using Microsoft.Coyote.Actors;5using Microsoft.Coyote.Specifications;6using Microsoft.Coyote.Tasks;7{8 {9 private static async Task Main(string[] args)10 {11 await Runtime.RunAsync(async () =>12 {13 var actor = Actor.CreateActorFromTask(async () =>14 {15 while (true)16 {17 await Task.Delay(100);18 }19 });20 var cachedDelegate = new CachedDelegate<bool>(actor, "IsCompletedSuccessfully");21 var result = cachedDelegate.Invoke();22 Console.WriteLine(result);23 });24 }25 }26}27using System;28using System.Threading.Tasks;29using Microsoft.Coyote;30using Microsoft.Coyote.Actors;31using Microsoft.Coyote.Tasks;32{33 {34 private static async Task Main(string[] args)35 {36 await Runtime.RunAsync(async () =>37 {38 var actor = Actor.CreateActorFromTask(async () =>39 {40 while (true)41 {42 await Task.Delay(100);43 }44 });45 var cachedDelegate = new CachedDelegate<bool>(actor, "IsCompletedSuccessfully");46 var result = cachedDelegate.Invoke();47 Console.WriteLine(result);48 });49 }50 }51}52The reason for this is that the CachedDelegate class uses the Task.GetAwaiter().GetResult() method to invoke the property. This method must be awaited, but the CachedDelegate class does not await it. This is

Full Screen

Full Screen

CachedDelegate

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using System.Threading.Tasks;5using Microsoft.Coyote;6using Microsoft.Coyote.Specifications;7using Microsoft.Coyote.Tasks;8{9 {10 public static async Task Main()11 {12 var cache = new CachedDelegate<object, object>(new Func<object, object>(x => x));13 var result = await cache.InvokeAsync(1);14 Console.WriteLine(result);15 }16 }17}18using System;19using System.Collections.Generic;20using System.Linq;21using System.Threading.Tasks;22using Microsoft.Coyote;23using Microsoft.Coyote.Specifications;24using Microsoft.Coyote.Tasks;25{26 {27 public static async Task Main()28 {29 var cache = new CachedDelegate<object, object>(new Func<object, object>(x => x));30 var result = await cache.InvokeAsync(1);31 Console.WriteLine(result);32 }33 }34}35using System;36using System.Collections.Generic;37using System.Linq;38using System.Threading.Tasks;39using Microsoft.Coyote;40using Microsoft.Coyote.Specifications;41using Microsoft.Coyote.Tasks;42{43 {44 public static async Task Main()45 {46 var cache = new CachedDelegate<object, object>(new Func<object, object>(x => x));47 var result = await cache.InvokeAsync(1);48 Console.WriteLine(result);49 }50 }51}52using System;53using System.Collections.Generic;54using System.Linq;55using System.Threading.Tasks;56using Microsoft.Coyote;57using Microsoft.Coyote.Specifications;58using Microsoft.Coyote.Tasks;59{60 {61 public static async Task Main()62 {63 var cache = new CachedDelegate<object, object>(new Func<object, object>(x => x));64 var result = await cache.InvokeAsync(1);65 Console.WriteLine(result);66 }67 }68}

Full Screen

Full Screen

CachedDelegate

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Specifications;2using System;3{4 {5 static void Main(string[] args)6 {7 var cachedDelegate = new CachedDelegate<int, int>(i => i * 2);8 }9 }10}11using Microsoft.Coyote.Specifications;12using System;13{14 {15 static void Main(string[] args)16 {17 var cachedDelegate = new CachedDelegate<int, int>(i => i * 2);18 var result = cachedDelegate.Invoke(

Full Screen

Full Screen

CachedDelegate

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Coyote.Specifications;4using Microsoft.Coyote.Tasks;5using Microsoft.Coyote.SystematicTesting;6using Microsoft.Coyote.Actors;7{8 {9 static void Main(string[] args)10 {11 var configuration = Configuration.Create().WithTestingIterations(10000);12 var test = new CachedDelegateTest();13 test.TestCachedDelegate(configuration);14 }15 }16 {17 public void TestCachedDelegate(Configuration configuration)18 {19 var runtime = RuntimeFactory.Create(configuration);20 runtime.RegisterMonitor(typeof(CachedDelegate));21 runtime.CreateActor(typeof(Actor1));22 runtime.Wait();23 }24 }25 {26 private CachedDelegate cachedDelegate;27 protected override Task OnInitializeAsync(Event initialEvent)28 {29 this.cachedDelegate = new CachedDelegate(this, "CachedDelegate");30 this.cachedDelegate.Start();31 return Task.CompletedTask;32 }33 protected override Task OnEventAsync(Event e)34 {35 if (e is CachedDelegateEvent)36 {37 this.cachedDelegate.Stop();38 this.cachedDelegate.Start();39 }40 return Task.CompletedTask;41 }42 }43 {44 private int count;45 [OnEntry(nameof(InitOnEntry))]46 [OnEventDoAction(typeof(CachedDelegateEvent), nameof(IncCount))]47 private class Init : MonitorState { }48 private void InitOnEntry()49 {50 this.count = 0;51 }52 private void IncCount()53 {54 this.count++;55 }56 protected override Task<bool> CheckHealthAsync(State state)57 {58 if (this.count > 1)59 {60 this.Assert(false, "CachedDelegate is not working as expected");61 }62 return Task.FromResult(true);63 }64 }65 { }66}67 at cachedDelegate.CachedDelegate.Assert(Boolean condition, String message) in 1.cs:line 8068 at cachedDelegate.CachedDelegate.CheckHealthAsync(State state) in 1.cs:line 7869 at Microsoft.Coyote.SystematicTesting.Runtime.MonitorRuntime.CheckMonitorsHealthAsync() in C:\Users\manas\Source

Full Screen

Full Screen

CachedDelegate

Using AI Code Generation

copy

Full Screen

1using System;2using Microsoft.Coyote.Specifications;3{4 public static void Main()5 {6 int i = 1;7 CachedDelegate d = new CachedDelegate(() => i * 2);8 Console.WriteLine(d.Invoke());9 i = 2;10 Console.WriteLine(d.Invoke());11 }12}13using System;14using Microsoft.Coyote.Specifications;15{16 public static void Main()17 {18 CachedDelegate d = new CachedDelegate(() => GetTime());19 Console.WriteLine(d.Invoke());20 System.Threading.Thread.Sleep(1000);21 Console.WriteLine(d.Invoke());22 }23 private static DateTime GetTime()24 {25 return DateTime.UtcNow;26 }27}28using System;29using Microsoft.Coyote.Specifications;30{31 public static void Main()32 {33 CachedDelegate d = new CachedDelegate((int i) => GetTime(i));34 Console.WriteLine(d.Invoke(1));35 System.Threading.Thread.Sleep(1000);36 Console.WriteLine(d.Invoke(2));37 System.Threading.Thread.Sleep(1000);

Full Screen

Full Screen

CachedDelegate

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Text;4using Microsoft.Coyote.Specifications;5{6 {7 public CachedDelegate(Func<int> f);8 public int Invoke();9 }10}11using System;12using System.Collections.Generic;13using System.Text;14using Microsoft.Coyote.Specifications;15{16 {17 public CachedDelegate(Func<int> f);18 public int Invoke();19 }20}21using System;22using System.Collections.Generic;23using System.Text;24using Microsoft.Coyote.Specifications;25{26 {27 public CachedDelegate(Func<int> f);28 public int Invoke();29 }30}31using System;32using System.Collections.Generic;33using System.Text;34using Microsoft.Coyote.Specifications;35{36 {37 public CachedDelegate(Func<int> f);38 public int Invoke();39 }40}41using System;42using System.Collections.Generic;43using System.Text;44using Microsoft.Coyote.Specifications;45{46 {47 public CachedDelegate(Func<int> f);48 public int Invoke();49 }50}51using System;52using System.Collections.Generic;53using System.Text;54using Microsoft.Coyote.Specifications;55{56 {57 public CachedDelegate(Func<int> f);58 public int Invoke();59 }60}61using System;62using System.Collections.Generic;63using System.Text;64using Microsoft.Coyote.Specifications;65{66 {67 public CachedDelegate(Func<int> f);68 public int Invoke();69 }70}

Full Screen

Full Screen

CachedDelegate

Using AI Code Generation

copy

Full Screen

1using System;2using Microsoft.Coyote.Specifications;3using Microsoft.Coyote.Specifications.Tasks;4using System.Threading.Tasks;5{6 {7 static void Main(string[] args)8 {9 Console.WriteLine("Hello World!");10 var task = Task.Run(() => { Console.WriteLine("Hello World!"); });11 CachedDelegate d = new CachedDelegate(task);12 d.Invoke();13 }14 }15}

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.

Run Coyote automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful