- Is there a reason to make every WCF call Async?
- public override User GetById(int id)
- {
- return new User(service.GetUserById(id));
- }
- public override void GetById(int id, Action<UserGroup> callback = null)
- {
- // This is a queue of all callbacks waiting for a GetById request
- if (AddToSelectbyIdQueue(id, callback))
- return;
- // Setup Async Call
- var wrapper = new AsyncPatternWrapper<UserDTO>(
- (cb, asyncState) => server.BeginGetUserById(id, cb, asyncState),
- Global.Instance.Server.EndGetUserById);
- // Hookup Callback
- wrapper.ObserveOnDispatcher().Subscribe(GetByIdCompleted);
- // Run Async Call
- wrapper.Invoke();
- }
- private void GetByIdCompleted(UserDTO dto)
- {
- User user = new User(dto);
- // This goes through the queue of callbacks waiting
- // for this method to complete and executes them
- RunSelectIdCallbacks(user.UserId, user);
- }
- /// <summary>
- /// Adds an item to the select queue, or a current fetch if there is one
- /// </summary>
- /// <param name="id">unique object identifier</param>
- /// <param name="callback">callback to run</param>
- /// <returns>False if it needs to be fetched, True if it is already being
- /// fetched</returns>
- protected virtual bool AddToSelectbyIdQueue(int id, Action<T> callback)
- {
- // If the id already exists we have a fetch function already going
- if (_selectIdCallbacks.ContainsKey(id))
- {
- if(callback != null)
- _selectIdCallbacks[id].Add(callback);
- return true;
- }
- if (callback != null)
- {
- List<Action<T>> callbacks = new List<Action<T>> {callback};
- _selectIdCallbacks.Add(id, callbacks);
- }
- return false;
- }
- /// <summary>
- /// Executes callbacks meant for that object Id and removes them from the queue
- /// </summary>
- /// <param name="id">unique identifier</param>
- /// <param name="data">Data for the callbacks</param>
- protected virtual void RunSelectIdCallbacks(int id, T data)
- {
- if (_selectIdCallbacks.ContainsKey(id))
- {
- foreach (Action<T> callback in _selectIdCallbacks[id])
- callback(data);
- _selectIdCallbacks.Remove(id);
- }
- }