In synchronous model it’s simply
using (MyServiceClient msc = new MyServiceClient())
{
msc.Method();
}
but if I must wait to end of this method, and then do something, it can’t work
private void EventHandler<MethodCompletedEventArgs> myEventHandler = new EventHandler<MethodCompletedEventArgs>(methodBody);
using (MyServiceClient msc = new MyServiceClient())
{
msc.MethdCompleted += myEventHandler;
msc.BeginMethod();
}
private void MethodBody()
{
//exception: client state is aborted
}
Also how to call async mehod in using statement?
You can store a reference to your service client and manually invoke its
Disposemethod once the event calls back. You just have to do some extra work managing exceptions and generally ensuring thatDisposeis called eventually. Also watch for conditions where you might create/overwrite multiple instances ofmscwhile waiting for an old one to complete:One way to make sure that you don’t dispose the wrong instance if you execute the same code multiple times is to use a local lambda/anonymous function:
It might get a bit messier than that; if an exception is thrown on
msc.BeginMethod()you should catch that as well and callDisposemost likely (but you don’t want to callDisposemore than once)