Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// A service that makes it easy to delay any call of a method and que the calls
- /// so that all other incoming calls get blocked of until the first call has been made.
- /// </summary>
- public class DelayedInvokingService
- {
- private List<string> DelayedMethodQue { get; }
- public DelayedInvokingService()
- {
- DelayedMethodQue = new List<string>();
- }
- /// <summary>
- /// Delay the call of a method by a given time and optionally block all other incoming
- /// calls of the specific method until the first delayed call is executed.
- /// </summary>
- /// <param name="delay_ms">The delay in milliseconds.</param>
- /// <param name="instance">A instance of the type to invoke the method with.</param>
- /// <param name="methodName">The name of the method.</param>
- /// <param name="block_other_calls">
- /// Set to true if you want block other incoming
- /// calls for the same method until the first call is done.
- /// </param>
- /// <param name="methodParameters">Method parameters to include when invoking the specified method.</param>
- public async void DelayMethodInvokation(int delay_ms, object instance, string methodName, bool block_other_calls = false, params object[] methodParameters)
- {
- // If que contains a element with the instance name and method name, we want to block all
- // incoming calls until the element was removed from the que.
- if (!DelayedMethodQue.Contains($"{instance.GetType().Name}{methodName}"))
- {
- // Add to que if we want to block all other incoming
- // calls until this call has been released
- if (block_other_calls)
- {
- DelayedMethodQue.Add($"{instance.GetType().Name}{methodName}");
- }
- // Delay the call
- await Task.Delay(delay_ms);
- // Invoke the method of the given instance with the given parameters
- instance.GetType().GetMethod(methodName).Invoke(instance, methodParameters);
- // Remove this call from the que
- DelayedMethodQue.Remove($"{instance.GetType().Name}{methodName}");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement