473,402 Members | 2,053 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,402 software developers and data experts.

using(object) ??

I used to wonder why MS implemented C# to accept the following code

using (Font f = new Font())
{
// some code here.
}

While the same can be achieved through

{
Font f = new Font()
// some code here.
}

Just making code as a block and create the object inside the block.
Why MS took pain to implement the semantics to understand in C# it as
in first block.

As per my understanding the above code does the following things
1. Creates a block where f is used
2. When code block completes execution, f is garbage collected.

I was wrong. There is one major significant difference between the two
code blocks.

Actually, what ever the object used in the using(object) statement,
has to implement IDisposable. I think by now you got the difference.
The beauty of the using(object) statement is that after the execution
of the using block object.Dispose() will be called by the framework,
releasing all the unmanaged resources.

See below code:

class TestC : IDisposable
{
public void UseLimitedResource()
{
Console.WriteLine("Using limited resource...");
}

void IDisposable.Dispose()
{
// this class uses significant unmanaged resources and are relesed
here.
Console.WriteLine("Disposing limited resource.");
}
}
class Program
{
static void Main(string[] args)
{
using (TestC testC = new TestC())
{
testC.UseLimitedResource();
}

Console.ReadLine();
}
}

However I ran into another BIG doubt that why C# allows the following
code

class Program
{
static void Main(string[] args)
{
TestC testC = new TestC()
using (testC)
{
testC.UseLimitedResource();
}

testC.UseLimitedResource();

Console.ReadLine();
}
}

Object is already disposed, still you can use it, driving to CRASHing
your own applications????
I appriciate your help to continue this...

-Cnu
Sep 10 '08 #1
12 1540
class TestC : IDisposable
{
private bool IsDisposed = false; //******

public void UseLimitedResource()
{
Console.WriteLine("Using limited resource...");
}

protected virtual void Dispose(bool disposing)
{
if (IsDisposed)
throw new ObjectDisposedException();

Console.WriteLine("Disposing limited resource.");
IsDisposed = true;
GC.SuppressFinalize(this);
}

void IDisposable.Dispose()
{
Dispose(true);
}

~TestC()
{
Dispose(false);
}

}
Sep 10 '08 #2
Peter Morris <mr*********@SPAMgmail.comwrote:
class TestC : IDisposable
{
private bool IsDisposed = false; //******

public void UseLimitedResource()
{
Console.WriteLine("Using limited resource...");
}

protected virtual void Dispose(bool disposing)
{
if (IsDisposed)
throw new ObjectDisposedException();

Console.WriteLine("Disposing limited resource.");
IsDisposed = true;
GC.SuppressFinalize(this);
}

void IDisposable.Dispose()
{
Dispose(true);
}

~TestC()
{
Dispose(false);
}

}
One issue with this: Dispose() shouldn't throw an exception when called
multiple times. From MSDN:

<quote>
If an object's Dispose method is called more than once, the object must
ignore all calls after the first one. The object must not throw an
exception if its Dispose method is called multiple times. Instance
methods other than Dispose can throw an ObjectDisposedException when
resources are already disposed.
</quote>

Personally I usually just seal the class and implement IDisposable
"simply" (and without a finalizer). The above more general pattern is
rarely necessary unless you're in complicated situations, IMO.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 10 '08 #3
On Sep 10, 8:57*am, "Peter Morris" <mrpmorri...@SPAMgmail.comwrote:
*class TestC : IDisposable
*{
* * private bool IsDisposed = false; //******

* * public void UseLimitedResource()
* * {
* * * * Console.WriteLine("Using limited resource...");
* * }

* * protected virtual void Dispose(bool disposing)
* * {
* * * * if (IsDisposed)
* * * * * * throw new ObjectDisposedException();

* * * * Console.WriteLine("Disposing limited resource.");
* * * * IsDisposed = true;
* * * * GC.SuppressFinalize(this);
* * }

* * void IDisposable.Dispose()
* * {
* * * * Dispose(true);
* * }

* * ~TestC()
* * {
* * * * Dispose(false);
* * }

*}
thats gre8, implementing a dispose() pattern suggested by MS.

However if my lazy developers does not implement this, and simply went
ahead with the code in the question, there must be a check from
runtime atleast for throwing an exception that object is already
disposed.

-Cnu.

Sep 10 '08 #4
On Wed, 10 Sep 2008 08:43:52 -0700, Duggi <Du***************@gmail.com>
wrote:
I used to wonder why MS implemented C# to accept the following code [...]
How is this different from the previous thread you started, and which you
finished up by saying that you got the "zest" of it?
Sep 10 '08 #5
On Sep 10, 9:16*am, Jon Skeet [C# MVP] <sk...@pobox.comwrote:
Peter Morris <mrpmorri...@SPAMgmail.comwrote:
*class TestC : IDisposable
*{
* * private bool IsDisposed = false; //******
* * public void UseLimitedResource()
* * {
* * * * Console.WriteLine("Using limited resource...");
* * }
* * protected virtual void Dispose(bool disposing)
* * {
* * * * if (IsDisposed)
* * * * * * throw new ObjectDisposedException();
* * * * Console.WriteLine("Disposing limited resource.");
* * * * IsDisposed = true;
* * * * GC.SuppressFinalize(this);
* * }
* * void IDisposable.Dispose()
* * {
* * * * Dispose(true);
* * }
* * ~TestC()
* * {
* * * * Dispose(false);
* * }
*}

One issue with this: Dispose() shouldn't throw an exception when called
multiple times. From MSDN:

<quote>
If an object's Dispose method is called more than once, the object must
ignore all calls after the first one. The object must not throw an
exception if its Dispose method is called multiple times. Instance
methods other than Dispose can throw an ObjectDisposedException when
resources are already disposed.
</quote>

Personally I usually just seal the class and implement IDisposable
"simply" (and without a finalizer). The above more general pattern is
rarely necessary unless you're in complicated situations, IMO.

--
Jon Skeet - <sk...@pobox.com>
Web site:http://www.pobox.com/~skeet*
Blog:http://www.msmvps.com/jon.skeet
C# in Depth:http://csharpindepth.com
Hi Jon,

<quote>
If an object's Dispose method is called more than once, the object
must
ignore all calls after the first one. The object must not throw an
exception if its Dispose method is called multiple times. Instance
methods other than Dispose can throw an ObjectDisposedException when
resources are already disposed.
</quote>

Is this by implementing dispose pattern, or by default runtime can do
it?

When I ran the code in the question... It ran perfectly.. without any
exception. I am little worried if any of my busy developers forget to
implement this.

-Cnu

Sep 10 '08 #6
On Sep 10, 9:42*am, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
On Wed, 10 Sep 2008 08:43:52 -0700, Duggi <DuggiSrinivasa...@gmail.com*
wrote:
I used to wonder why MS implemented C# to accept the following code [....]

How is this different from the previous thread you started, and which you*
finished up by saying that you got the "zest" of it?
Apologies to all in this thread!!!

Yesterday night I tried asking a question with the title " using
(object) a Mystery for me!!! "

And the groups site displayed an error while posting it... however it
got posted correctly... here is the link
http://groups.google.com/group/micro...5000037a06e7b9

that why I stated a new thread / question.
The other question I had was about the XmlSerialization class... which
I got clarified with you. I am thankful to you for your valuable
replies. They helped me in understanding the XML Serialization class
more properly.

here is the link..
http://groups.google.com/group/micro...ed5934c71ba19e

The current question is about using(object)

-Cnu

Sep 10 '08 #7
Duggi <Du***************@gmail.comwrote:
<quote>
If an object's Dispose method is called more than once, the object
must
ignore all calls after the first one. The object must not throw an
exception if its Dispose method is called multiple times. Instance
methods other than Dispose can throw an ObjectDisposedException when
resources are already disposed.
</quote>

Is this by implementing dispose pattern, or by default runtime can do
it?
That's when you implement IDisposable.
When I ran the code in the question... It ran perfectly.. without any
exception. I am little worried if any of my busy developers forget to
implement this.
How often do you implement IDisposable yourself? How often do you write
a using statement which *doesn't* declare a variable and create a new
instance of whatever you're using?

A modicum of care is required, but that's all.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 10 '08 #8
On Sep 10, 9:54*am, Jon Skeet [C# MVP] <sk...@pobox.comwrote:
Duggi <DuggiSrinivasa...@gmail.comwrote:
<quote>
If an object's Dispose method is called more than once, the object
must
ignore all calls after the first one. The object must not throw an
exception if its Dispose method is called multiple times. Instance
methods other than Dispose can throw an ObjectDisposedException when
resources are already disposed.
</quote>
Is this by implementing dispose pattern, or by default runtime can do
it?

That's when you implement IDisposable.
When I ran the code in the question... It ran perfectly.. without any
exception. I am little worried if any of my busy developers forget to
implement this.

How often do you implement IDisposable yourself? How often do you write
a using statement which *doesn't* declare a variable and create a new
instance of whatever you're using?

A modicum of care is required, but that's all.

--
Jon Skeet - <sk...@pobox.com>
Web site:http://www.pobox.com/~skeet*
Blog:http://www.msmvps.com/jon.skeet
C# in Depth:http://csharpindepth.com
Thanks Jon,

I understand that Dispose pattern is the solution for the bad code in
question. I really understand the importance of the dispose pattern
now.

Thanks to all of you in the discussion for your valuable time.

-Cnu

PS: I am trying to get myself more and more familier with .Net and C#.
If at all I ask any dumb dumb questions, please understand my level of
expertise.

Sep 10 '08 #9
Duggi wrote:
<quote>
If an object's Dispose method is called more than once, the object
must
ignore all calls after the first one. The object must not throw an
exception if its Dispose method is called multiple times. Instance
methods other than Dispose can throw an ObjectDisposedException when
resources are already disposed.
</quote>

Is this by implementing dispose pattern, or by default runtime can do
it?

When I ran the code in the question... It ran perfectly.. without any
exception. I am little worried if any of my busy developers forget to
implement this.

-Cnu
According to the guidelines, you should be able to do this:

TestC test = new TestC();
test.Dispose();
test.Dispose();

If the second call to Dispose throws an exception (which the code from
Peter Morris does), it doesn't follow the guidelines.

--
Göran Andersson
_____
http://www.guffa.com
Sep 10 '08 #10
Duggi,

I strongly get the idea that you have a wrong idea what dispose does.

It releases the unmanaged "resources".

It does not release an object, that is done by the GC. Which surely does not
start when something goes out of scope as you wrote. It is done time by time
which can even be at the end of the program.

A lot of managed code is still only a wrapper around old com objects, as you
see strongly in Sharepoint.
As you are doing something for SharePoint, then it is good practise to use
dispose on every object or use using as that is automaticly done then. The
latter is surely not in general. As you look at most Data (SQL) classes
(including Linq) the dispose does almost nothing, is simple not there or/and
is wrapped in the close method.

Cor

"Duggi" <Du***************@gmail.comschreef in bericht
news:e8**********************************@k36g2000 pri.googlegroups.com...
>I used to wonder why MS implemented C# to accept the following code

using (Font f = new Font())
{
// some code here.
}

While the same can be achieved through

{
Font f = new Font()
// some code here.
}

Just making code as a block and create the object inside the block.
Why MS took pain to implement the semantics to understand in C# it as
in first block.

As per my understanding the above code does the following things
1. Creates a block where f is used
2. When code block completes execution, f is garbage collected.

I was wrong. There is one major significant difference between the two
code blocks.

Actually, what ever the object used in the using(object) statement,
has to implement IDisposable. I think by now you got the difference.
The beauty of the using(object) statement is that after the execution
of the using block object.Dispose() will be called by the framework,
releasing all the unmanaged resources.

See below code:

class TestC : IDisposable
{
public void UseLimitedResource()
{
Console.WriteLine("Using limited resource...");
}

void IDisposable.Dispose()
{
// this class uses significant unmanaged resources and are relesed
here.
Console.WriteLine("Disposing limited resource.");
}
}
class Program
{
static void Main(string[] args)
{
using (TestC testC = new TestC())
{
testC.UseLimitedResource();
}

Console.ReadLine();
}
}

However I ran into another BIG doubt that why C# allows the following
code

class Program
{
static void Main(string[] args)
{
TestC testC = new TestC()
using (testC)
{
testC.UseLimitedResource();
}

testC.UseLimitedResource();

Console.ReadLine();
}
}

Object is already disposed, still you can use it, driving to CRASHing
your own applications????
I appriciate your help to continue this...

-Cnu
Sep 10 '08 #11
Yeah, I was rushing and instead of throwing the exception in the property
getter that read the resource I just wrote the code in the Dispose method.
I think I just saw the words "limited resource" and wrote the code straight
in to throw the exception. :-)

Sep 10 '08 #12
On 10 Sep, 22:56, "Cor Ligthert[MVP]" <notmyfirstn...@planet.nl>
wrote:
Duggi,

I strongly get the idea that you have a wrong idea what dispose does.

It releases the unmanaged "resources".

It does not release an object, that is done by the GC. Which surely does not
start when something goes out of scope as you wrote. It is done time by time
which can even be at the end of the program.

A lot of managed code is still only a wrapper around old com objects, as you
see strongly in Sharepoint.
As you are doing something for SharePoint, then it is good practise to use
dispose on every object or use using as that is automaticly done then. The
latter is surely not in general. As you look at most Data (SQL) classes
(including Linq) the dispose does almost nothing, is simple not there or/and
is wrapped in the close method.

Cor

"Duggi" <DuggiSrinivasa...@gmail.comschreef in berichtnews:e8**********************************@k 36g2000pri.googlegroups.com...
I used to wonder why MS implemented C# to accept the following code
using (Font f = new Font())
{
* * *// some code here.
}
While the same can be achieved through
{
Font f = new Font()
* * *// some code here.
}
Just making code as a block and create the object inside the block.
Why MS took pain to implement the semantics to understand in C# it as
in first block.
As per my understanding the above code does the following things
1. Creates a block where f is used
2. When code block completes execution, f is garbage collected.
I was wrong. There is one major significant difference between the two
code blocks.
Actually, what ever the object used in the using(object) statement,
has to implement IDisposable. I think by now you got the difference.
The beauty of the using(object) statement is that after the execution
of the using block object.Dispose() will be called by the framework,
releasing all the unmanaged resources.
See below code:
class TestC : IDisposable
{
* * * *public void UseLimitedResource()
* * * *{
* * * * * *Console.WriteLine("Using limited resource...");
* * * *}
* * * *void IDisposable.Dispose()
* * * *{
// this class uses significant unmanaged resources and are relesed
here.
* * * * * *Console.WriteLine("Disposing limited resource.");
* * * *}
}
class Program
{
static void Main(string[] args)
* * *{
* * * * * *using (TestC testC = new TestC())
* * * * * *{
* * * * * * * *testC.UseLimitedResource();
* * * * * *}
* * * * * *Console.ReadLine();
* * * }
}
However I ran into another BIG doubt that why C# allows the following
code
class Program
{
static void Main(string[] args)
* * *{
TestC testC = new TestC()
* * * * * *using (testC)
* * * * * *{
* * * * * * * *testC.UseLimitedResource();
* * * * * *}
testC.UseLimitedResource();
* * * * * *Console.ReadLine();
* * * }
}
Object is already disposed, still you can use it, driving to CRASHing
your own applications????
I appriciate your help to continue this...
-Cnu
Thanks Cor,

I got one practical use case of the scenario where allowing the above
code makes sense. I understand that a little care is required while
using the object that is disposed. Thanks for throwing light on it.

Thanks
-Cnu
Sep 11 '08 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Joe Kelsey | last post by:
When you use addEventListener (or addEvent in IE) to call an object method, does it call it with the correct this parameter? The ECMAScript reference has a lot to say about the caller using...
0
by: Aleksey Dmitriyev | last post by:
I am using Session property for my own serializable objects. The code snippet is below: // C# ASP.NET code behind private void btnRun_Click(object sender, System.EventArgs e) { MyClass myObj...
7
by: William Apple | last post by:
Despite the fact this deals with webservices I believe it is a VB question. I am working on a test application that passes data to a webservice. The webservices takes a variable type that is...
1
by: Ram | last post by:
Hi All, I am using Object Data Source to bind data in the gridview. I have set the property AllowSorting=true. While running the application, I could sort the data only in ascending order. Is...
6
by: burningodzilla | last post by:
Hi all - I'm preparing to dive in to more complex application development using javascript, and among other things, I'm having a hard time wrapping my head around an issues regarding "inheritance"...
0
by: sajithamol | last post by:
I have a dll of a VB application which performs image manipulations. I want to build this dll file into a .cab file to embed this in the Object tag in client side. Also how to generate the classid...
2
by: Veloz | last post by:
Hiya My question is whether or not you should associated related objects in your software using a scheme of id's and lookups, or wether objects should actually hold actual object references to...
0
by: =?Utf-8?B?UGF1bA==?= | last post by:
Hi I have a gridview that binds to an object datasource. I added an update method to the object data source through the wizard. The update method takes an object as input and returns an object of...
9
by: Duggi | last post by:
I used to wonder why MS implemented C# to accept the following code using (Font f = new Font()) { // some code here. } While the same can be achieved through {
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.