Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. /// <summary>
  2. /// A service that makes it easy to delay any call of a method and que the calls
  3. /// so that all other incoming calls get blocked of until the first call has been made.
  4. /// </summary>
  5. public class DelayedInvokingService
  6. {
  7. private List<string> DelayedMethodQue { get; }
  8.  
  9. public DelayedInvokingService()
  10. {
  11. DelayedMethodQue = new List<string>();
  12. }
  13.  
  14. /// <summary>
  15. /// Delay the call of a method by a given time and optionally block all other incoming
  16. /// calls of the specific method until the first delayed call is executed.
  17. /// </summary>
  18. /// <param name="delay_ms">The delay in milliseconds.</param>
  19. /// <param name="instance">A instance of the type to invoke the method with.</param>
  20. /// <param name="methodName">The name of the method.</param>
  21. /// <param name="block_other_calls">
  22. /// Set to true if you want block other incoming
  23. /// calls for the same method until the first call is done.
  24. /// </param>
  25. /// <param name="methodParameters">Method parameters to include when invoking the specified method.</param>
  26. public async void DelayMethodInvokation(int delay_ms, object instance, string methodName, bool block_other_calls = false, params object[] methodParameters)
  27. {
  28. // If que contains a element with the instance name and method name, we want to block all
  29. // incoming calls until the element was removed from the que.
  30. if (!DelayedMethodQue.Contains($"{instance.GetType().Name}{methodName}"))
  31. {
  32. // Add to que if we want to block all other incoming
  33. // calls until this call has been released
  34. if (block_other_calls)
  35. {
  36. DelayedMethodQue.Add($"{instance.GetType().Name}{methodName}");
  37. }
  38.  
  39. // Delay the call
  40. await Task.Delay(delay_ms);
  41.  
  42. // Invoke the method of the given instance with the given parameters
  43. instance.GetType().GetMethod(methodName).Invoke(instance, methodParameters);
  44.  
  45. // Remove this call from the que
  46. DelayedMethodQue.Remove($"{instance.GetType().Name}{methodName}");
  47. }
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement