Saint
Saint

Reputation: 5469

How to call asynchronous wcf method in using statement?

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?

Upvotes: 1

Views: 695

Answers (2)

Chris Sinclair
Chris Sinclair

Reputation: 23208

You can store a reference to your service client and manually invoke its Dispose method once the event calls back. You just have to do some extra work managing exceptions and generally ensuring that Dispose is called eventually. Also watch for conditions where you might create/overwrite multiple instances of msc while 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:

MyServiceClient msc = new MyServiceClient();

msc.MethdCompleted += (sender, args) => 
{
    try
    {
        myEventHandler(sender, args);
    }
    finally
    {
        msc.Dispose();
    }
};

msc.BeginMethod();

It might get a bit messier than that; if an exception is thrown on msc.BeginMethod() you should catch that as well and call Dispose most likely (but you don't want to call Dispose more than once)

Upvotes: 1

Roy Dictus
Roy Dictus

Reputation: 33139

You should not do this.

You should instantiate MyServiceClient normally, then Dispose of it in the async callback handler.

This is the only way to ensure that the instance will still exist once the callback handler is called, and that it is destroyed after the callback handler has finished its work.

Upvotes: 6

Related Questions