Mako
Mako

Reputation: 1515

Cannot access a disposed object exception in WCF

I am using the following code to call WCF service methods

MyServiceClient proxy = new MyServiceClient();
proxy.Open();
proxy.Func1();
proxy.Close();
// Some other code
proxy.Open();
proxy.Func2();

proxy.Close();

I get the exception while calling the 'proxy.Open()' second time but sometimes the code works. I can also use the following code shown below which works fine.

MyServiceClient proxy = new MyServiceClient();

proxy.Func1();

// Some other code

proxy.Func2();

proxy.Close();

I also want to know which is the better way of calling the functions. Which approach will give better performance ?

Upvotes: 7

Views: 5216

Answers (4)

Sixto Saez
Sixto Saez

Reputation: 12680

WCF is one of few instance (possibly only instance) in the .NET framework where you should NOT use the using statement with a class that implements IDisposable. This MSDN Article explains the correct pattern for using service references. This also applies to Channel instances created from ChannelFactory.

Upvotes: 5

Lev
Lev

Reputation: 3924

As others have already mentioned you should worry about deterministic release of resources after calling Close() method, but if Exception occurs in Func1,2() methods external resources will not be released.

I suggest you to use using and IDisposable pattern, that means everytime you want to make service call use:

using(MyServiceClient proxy = new MyServiceClient())
{
    proxy.Func1();
}

which guarantees that all resources will be released even if something goes wrong within braces. Or you can do this manually with try, finally combination.

Upvotes: 0

lcryder
lcryder

Reputation: 496

Use the same proxy over multiple calls

MyServiceClient proxy = new MyServiceClient();
proxy.Open();
proxy.Func1();

// Some other code

proxy.Func2();
proxy.Close();

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564461

Once you close a connection, you can't reuse it.

You need to make a new MyServiceClient at that point.

MyServiceClient proxy = new MyServiceClient();
proxy.Open();
proxy.Func1();
proxy.Close();

// Some other code

proxy = new MyServiceClient(); // Recreate the client here
proxy.Open();
proxy.Func2();
proxy.Close();

Upvotes: 9

Related Questions