Guest User

Untitled

a guest
Jul 4th, 2012
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. Is there a reason to make every WCF call Async?
  2. public override User GetById(int id)
  3. {
  4. return new User(service.GetUserById(id));
  5. }
  6.  
  7. public override void GetById(int id, Action<UserGroup> callback = null)
  8. {
  9. // This is a queue of all callbacks waiting for a GetById request
  10. if (AddToSelectbyIdQueue(id, callback))
  11. return;
  12.  
  13. // Setup Async Call
  14. var wrapper = new AsyncPatternWrapper<UserDTO>(
  15. (cb, asyncState) => server.BeginGetUserById(id, cb, asyncState),
  16. Global.Instance.Server.EndGetUserById);
  17.  
  18. // Hookup Callback
  19. wrapper.ObserveOnDispatcher().Subscribe(GetByIdCompleted);
  20.  
  21. // Run Async Call
  22. wrapper.Invoke();
  23. }
  24.  
  25. private void GetByIdCompleted(UserDTO dto)
  26. {
  27. User user = new User(dto);
  28.  
  29. // This goes through the queue of callbacks waiting
  30. // for this method to complete and executes them
  31. RunSelectIdCallbacks(user.UserId, user);
  32. }
  33.  
  34. /// <summary>
  35. /// Adds an item to the select queue, or a current fetch if there is one
  36. /// </summary>
  37. /// <param name="id">unique object identifier</param>
  38. /// <param name="callback">callback to run</param>
  39. /// <returns>False if it needs to be fetched, True if it is already being
  40. /// fetched</returns>
  41. protected virtual bool AddToSelectbyIdQueue(int id, Action<T> callback)
  42. {
  43. // If the id already exists we have a fetch function already going
  44. if (_selectIdCallbacks.ContainsKey(id))
  45. {
  46. if(callback != null)
  47. _selectIdCallbacks[id].Add(callback);
  48. return true;
  49. }
  50.  
  51. if (callback != null)
  52. {
  53. List<Action<T>> callbacks = new List<Action<T>> {callback};
  54. _selectIdCallbacks.Add(id, callbacks);
  55. }
  56.  
  57. return false;
  58. }
  59.  
  60. /// <summary>
  61. /// Executes callbacks meant for that object Id and removes them from the queue
  62. /// </summary>
  63. /// <param name="id">unique identifier</param>
  64. /// <param name="data">Data for the callbacks</param>
  65. protected virtual void RunSelectIdCallbacks(int id, T data)
  66. {
  67. if (_selectIdCallbacks.ContainsKey(id))
  68. {
  69. foreach (Action<T> callback in _selectIdCallbacks[id])
  70. callback(data);
  71.  
  72. _selectIdCallbacks.Remove(id);
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment