views:

134

answers:

2

I'm trying to make calls sync. But silverlight app locks itself when calling endList method. In a simple console app i can make async to sync. Could not see the problem.

  var svc = new WcfServiceClient();
  var ar = svc.BeginList(null, null);
  var result = svc.EndList(ar); <-- Silverlight hangs here
  listBox.ItemsSource = result;
+1  A: 

Silverlight doesn't support Sync calls.

Here is a article about synchronous calls to webservices and a workaround.

rdkleine
A: 

Short answer: You can do that if you are not on the Dispatcher thread, something like:

System.Threading.ThreadPool.QueueUserWorkItem(state =>
    {
        IAsyncResult asyncResult = svc.BeginSomething(null, null);

        if (!asyncResult.CompletedSynchronously)
        {
            asyncResult.AsyncWaitHandle.WaitOne();
        }

        try
        {
            svc.EndSomething(asyncResult);
        }
        catch
        {
            throw;
        }
        finally
        {
            asyncResult.AsyncWaitHandle.Close();
        }
    });

The big advantage of this is that you can keep your domain model layer synchronously like in the old days, you can implement lazy loading easily etc...

But in practice you can only use it when you design your application to strictly adhere to the MVVM / Commanding patterns, where your ViewModels and Commands handle the switching between the dispatcher thread and the model threads. It's a lot of ground work to do, and there are some gotchas, but when it works, it works wonderfully.

If you want to use ready-to-use framework that works similarly, it is available here: CodeProject: Introducing the Model Thread View Thread Pattern. The architecture is explained very well too on that page.

herzmeister der welten