A colleague of mine asked me how to chain service calls in a Silverlight async model.
Lets say you have these two operations:
string GetId()
void Calculate(string id)
And you must call GetId first and then use the result of that operation to call the Calculate operation.
The solution is pretty simple. We can use our old friend; the AutoResetEvent class. Luckly this exist in Silverlight as well.
First we put the task on the ThreadPool so we don’t block the UI Thread:
private void Button_Click(object sender, RoutedEventArgs e) { ThreadPool.QueueUserWorkItem(StartWork); }
And here is the StartWork method:
public void StartWork(object state) { var dataService = new DataServiceClient(); var personService = new PersonServiceClient(); string id = string.Empty; dataService.GetIdCompleted += (s, e) => { id = e.Result; //signal the event, so the thread can continue autoResetEvent.Set(); }; //call GetIdAsync dataService.GetIdAsync(); //pause the thread autoResetEvent.WaitOne(); //call CalculateAsync with the id personService.CalculateAsync(id); }
No comments:
Post a Comment