Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access a disposed object exception in WCF

Tags:

.net

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 ?

like image 933
Mako Avatar asked Sep 23 '13 18:09

Mako


2 Answers

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();
like image 123
Reed Copsey Avatar answered Sep 23 '22 07:09

Reed Copsey


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.

like image 32
Sixto Saez Avatar answered Sep 24 '22 07:09

Sixto Saez