views:

5935

answers:

4

Hi!

Sometimes I need to call WCF service in Silverlight and block UI until it returns. Sure I can do it in three steps:

  1. Setup handlers and block UI
  2. Call service
  3. Unblock UI when everything is done.

However, I'd like to add DoSomethingSync method to service client class and just call it whenever I need.

Is it possible? Has anyone really implemented such a method?

UPDATE: Looks like the answer is not to use sync calls at all. Will look for some easy to use pattern for async calls. Take a look at this post (taken from comments) for more.

+4  A: 

Here's the point; you shouldn't do sync IO in Silverlight. Stop fighting it! Instead:

  • disable any critical parts of the UI
  • start async IO with callback
  • (...)
  • in the callback, process the data and update/re-enable the UI

As it happens, I'm actively working on ways to make the async pattern more approachable (in particular with Silverlight in mind). Here's a first stab, but I have something better up my sleeve ;-p

Marc Gravell
That's always a question for me - why? We can do sync calls to WCF everywhere (WinForms, WPF etc.) and we can run into same issues. What's so different about Silverlight?
Nikolay R
(answered as a comment on your question)
Marc Gravell
+1  A: 

I'd disagree with Marc there are genuine cases where you need to do synchronous web service calls. However what you probably should avoid is blocking on the UI thread as that creates a very bad user experience.

A very simple way to implement a service call synchronously is to use a ManualResetEvent.

ManualResetEvent m_svcMRE = new ManualResetEvent(false);
MyServiceClient m_svcProxy = new MyServiceClient(binding, address);
m_svcProxy.DoSomethingCompleted += (sender, args) => {  m_svcMRE.Set(); };

public void DoSomething()
{
    m_svcMRE.Reset();
    m_svcProxy.DoSomething();
    m_svcMRE.WaitOne();
}
sipwiz
If you run DoSomething on the main thread, your application will hang.
Thats right and thats why I did mention you shouldn't run it on your main UI thread.
sipwiz
Tried to implement it but it never worked :(
Nikolay R
A: 

Here's a class that will let you synchronously call WCF services in SL: http://johnleitch.blogspot.com/2010/03/easy-way-to-synchronously-call-wcf.html

John Leitch