Here's a bug that has driven me nuts over the past few days. I have a WPF application that communicates with a pretty basic WCF service. Whenever a callback is issued in the middle of a request, the WPF application completely hangs. It's obviously a synchronization issue, however I've gone through the forums and articles and set every imaginable attribute on every imaginable object with no successful outcome.
In the end, the answer was unexpectedly simple, however not one I would have ever guessed. I accidentally stumbled across the solution during a round of trying totally crazy things in an attempt to make something work. All I had to do was create my channel on a thread other than the application's main thread. Let me demonstrate with some examples.
public partial class Window1 : Window
{
IStringReverser _channel;
public Window1()
{
InitializeComponent();
Callbacks callbacks = new Callbacks(_btnReverse);
var factory = new DuplexChannelFactory<IStringReverser>(
callbacks,
new NetNamedPipeBinding(),
new EndpointAddress(
"net.pipe://localhost/PipeReverse"));
_channel = factory.CreateChannel();
}
private void _btnReverse_Click(object sender, RoutedEventArgs e)
{
//ReverseString results in the server firing a callback.
//Making this call will freeze the application.
_channel.ReverseString("Hello World");
}
}
The interfaces and most of the code is from a previous tutorial. If the correct attributes are not set on the client's implementation of the callback interface and the server's implementation of the service contract, I would actually expect a deadlock to occur, however the app still hangs regardless of the configuration.
The solution is to simply wrap the CreateChannel call in a new thread.
public partial class Window1 : Window
{
IStringReverser _channel;
public Window1()
{
InitializeComponent();
Callbacks callbacks = new Callbacks(_btnReverse);
var factory = new DuplexChannelFactory<IStringReverser>(
callbacks,
new NetNamedPipeBinding(),
new EndpointAddress(
"net.pipe://localhost/PipeReverse"));
ThreadPool.QueueUserWorkItem(new WaitCallback(
(obj) =>
{
_channel = factory.CreateChannel();
}));
}
private void _btnReverse_Click(object sender, RoutedEventArgs e)
{
//This call no longer freezes the app
//and the callback is received correctly.
_channel.ReverseString("Hello World");
}
}
The callback now works without hanging the application, but there's one
more hurdle. In order to do anything to the user interface, you're going
to have to use the dispatcher and invoke a call. If you do this, the
application will again hang - invoking onto the UI thread is exactly
what got us into this mess in the first place. This can be easily fixed
by using the dispatcher's BeginInvoke function.
public void MyCallbackFunction(string callbackValue)
{
//doing this will hang the application
_dispatcher.Invoke(new Action(
() => _someControl.Text = callbackValue;));
//this will not cause the application to hang
_dispatcher.BeginInvoke(new Action(
() => _someControl.Text = callbackValue;));
}
The _dispatcher variable is something you're going to have to get a
hold of at some point during the creation of the callback interface. I
typically create the interface on the UI thread then simply call
Dispatcher.CurrentDispatcher and save that to my variable.
I've read several things stating that all that's actually required is to
set the IsOneWay property on the callback's OperationContract
attribute. In theory, that's how it should work, since if that is true,
WCF will not perform any locking when sending that data. Unfortunately,
that doesn't work. You should still keep that property set though, since
it does other things you really will want.
The other major piece of information I came across was the
UseSynchronizationContext property on the callback implementation's
ServiceBehavior attribute. This one sounded really promising. When set
to false, the callback will not automatically synchronize with the UI
thread. This seems to be the source of the deadlock anyway, so I thought
this was definitely it, but again, no luck.
All-in-all it came down to a simple fix that required a lot of headache to find. I'm not totally happy with the outcome, so if anyone else out there experienced this problem and has found a real solution, please let me know.
Edit: Check out this solution recommended by an alert reader to this problem.
[CallbackBehavior(ConcurrencyMode=ConcurrencyMode.Multiple, UseSynchronizationContext=false)]
At least in the original example, the callback interface didn't have any service attributes. Adding
solved the apparently same issue for me...
See, that's why I love this place. I kept applying a
ServiceBehaviorto the Callback implementation instead of aCallbackBehavior. Your solution works perfectly.bump.
This solution seems to be the way to go.
This has gotten us past our deadlock issues.
This is exactly what I needed, thank you very much!
Thank you very much!!! It works!!!
i have same problem and set ConcurrencyMode=ConcurrencyMode.Multiple, UseSynchronizationContext=false) on wcf, my problem solved
thank you Anon...
THANKS Anon, you made my day! :D
More sentiments of "need to buy you a beer"! Thankyou so much for this solution.... would help if the MSDN docs were *ahem* a little clearer on that one! :)
Sorry, I should have quoted/copied.
This is the solution that worked for us.
04/20/2009 - 14:22
At least in the original example, the callback interface didn't have any service attributes. Adding [CallbackBehavior(ConcurrencyMode=ConcurrencyMode.Multiple, UseSynchronizationContext=false)] solved the apparently same issue for me...
thank you so much - just what I needed!
excellent job!!
Same for me - I had the problem that a callback method implementation was not able to re-invoke the server. Of course, I've tried it with ____ServiceBehavior____(ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext = false) - It took ages until I found Anon's post or better, Reddest's reply to it and realized that I did exactly the same mistake.
great small easily added in my solution for a first version.. one thing about the threadpool : does it also handle many callback on duplexcommunicationchannel dcc through different subthread or is it only available for the object dcc ?
Thanks guys. I spent a full day trying to figure out why my client app was hanging. Adding [CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext = false)] to the clint class that implements the callback interface fixed my problem.
Ah, ah, thank you. I had only
Added
and its working with Invoke() :) Thanks Anon and { }
Good
Thanks a lot. Tum jiyo hazaaron saal (in hindi)
Thanks! Excelent solution!
> Adding [CallbackBehavior(ConcurrencyMode=ConcurrencyMode.Multiple, UseSynchronizationContext=false)] solved the apparently same issue for me...
Thank you, thank you, thank you, thank you :)
We've been having this happen intermittently, and unfortunately it's not consistently reproducible. Sounds like the exact same scenario though. I'd like to give your solution a shot, is there any chance you can explain why this works? Much appreciated!
Thanks a lot. I have been working for this error for two days. :)
Thanks. From above example i understand first time, what WCF is.
This does not work if you try to send back a large byte array. The error says bad request on the service. My code works using a console application client but not a wpf client.
Can someone confirm this? I used the code below to do the callback
public void TestCallback() { byte j = 0; byte[] largeArray = new byte[153600]; for (int i = 0; i \< largeArray.Length; i++) { largeArray[i] = j; if (j > 255) j = 0; }
ICallbacks callbacks = OperationContext.Current.GetCallbackChannel(); callbacks.MyCallbackFunction(largeArray); }
You can ignore the post above. My config file was ignored by my application. Its fixed now.
Many thank for the idea with the ThreadPool. I've set the concurrency mode to multiple and the sync context to false, but I also had no luck until I found your workaround. But it still bothers me why we have to create the channel on a separate thread.
Thanks for the post. Just one question. If you create _channel using ThreadPool, _channel creation may be is not completed, when you call _btnReverse_Click() function? Isn't so? Thank you.
Dude... you're an absolute genius!!! I can't believe how much time I've spent trying to figure this out. I was literally seconds away from giving up and trying something else until I saw your post. Fantastic!!! It's folks like you that really contribute these kind of real-world experiences to the .Net community... we sure know there's not enough in the MSDN library to help figure things like this out. Thanks!!!!!!
thanks buddy its works perfectly :)
I was trapped in a scenario where neither the callback nor the service behavior solve the problem. The situation showed up as a timeout during a service call in a duplex channel configuration. The setup is a WinForms application communicating (as client) via named pipes to a separate process (the server) it started.
After a few successful calls (in both directions, even nested) the WCF-tracing revealed that one server-response did not reach the client side (although it was transmitted according to the server log and confirmed by debugging), ultimatively resulting in a timeout on the client side.
Strange thing is the timeout happens on one of the "normal" two-way/request-response method of the service nested in a call chain initiated by a server callback.
I set ConcurrencyMode to multiple and UseSynchronizationContext to false on both sides but it didn't work until I created the client channel on a different thread - as orignally supposed.
Thanks For your beautiful article.it helped me a lot. i have a problem.that console applications(in previous artivle about WCF) run well and there was not any problem. I decided to convert them to Winform,i did all but i do not know what should i do with dispatcher part?
does winform have dispatcher like WPF?can you explain a little for me that what should i write in MyCallbackFunction?
without doing works about dispatcher i get following error on _channel.ReverseString in client project: There was no endpoint listening at net.pipe://localhost/PipeReverse that could accept the message
thanks so much for your help
how do u create dispatcher object. u did not define it in code previously. what kind of object it is dispatcher ??
give the full code. thanks