views:

645

answers:

1

I have a question regarding the sequencing of events in the scenario where you are calling a wcf service from silverlight 3 and updating the ui on a seperate thread. Basically, I would like to know whether what I am doing is correct... Sample is as follows. This is my first post on here, so bear with me, because i am not sure how to post actual code. Sample is as follows :

//<summary>
public static void Load(string userId)
{

  //Build the request.
  GetUserNameRequest request =
    new GetUserNameRequest { UserId = userId };

  //Open the connection.
  instance.serviceClient = ServiceController.UserService;

  //Make the request.
  instance.serviceClient.GetUserNameCompleted
    += UserService_GetUserNameCompleted;

  instance.serviceClient.GetGetUserNameAsync(request);

  return instance.VM;
}

/// <summary>
private static void UserService_GetUserNameCompleted(object sender, GetUserNameCompletedEventArgs e)
{
  try
  {
    Controller.UIDispatcher.BeginInvoke(() =>
    {
      //Load the response.
      if (e.Result != null && e.Result.Success)
      {
        LoadResponse(e.Result);
      }

      //Completed loading data.
    });
   } 
   finally
   {
     instance.serviceClient.GetUserNameCompleted 
       -= UserService_GetUserNameCompleted;

     ServiceHelper.CloseService(instance.serviceClient);
   }
}

So my question basically is, inside of my UI thread when I am loading the response if that throws an exception, will the "finally" block catch that ? If not, should i put another try/catch inside of the lambda where I am loading the response ?

Also, since I am executing the load on the ui thread, is it possible that the finally will execute before the UI thread is done updating ? And could as a result call the Servicehelper.CloseService() before the load has been done ?

I ask because I am having intermittent problems using this approach.

A: 

The finally block should get executed before the processing of the response inside the BeginInvoke. BeginInvoke means that the code will get executed in the next UI cycle.

Typically the best approach to this type of thing is to pull all the data you need out of the response and store it in a variable and then clean up your service code. Then make a call to BeginInvoke and update the UI using the data in the variable.

Bryant