Finalize method guidelines and best practices in C# [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have recently encountered an issue that is related to code running in the Finalize method overload.
I am mostly aware of issues that are related to memory management/performance, but i am interested whether there are any guidelines for "which code should/shouldn't go in a Finalize method" ?
For example:
Do not throw exceptions from within a Finalize method.
Code should execute quickly.
Do not raise events (?)
Etc...
The behaviour in my case was seen due to an event being raised that caused some exception.
So my question is -- what guidelines must i follow (perhaps even enforce using some tools) regarding finalize methods?

Finalizing is ONLY for getting rid of unmanaged resources
From MSDN
If Finalize or an override of Finalize throws an exception, and the runtime is not hosted by an application that overrides the default policy, the runtime terminates the process and no active try-finally blocks or finalizers are executed. This behavior ensures process integrity if the finalizer cannot free or destroy resources.
Finalize operations have the following limitations:
The exact time when the finalizer executes during garbage collection is undefined. Resources are not guaranteed to be released at any specific time, unless calling a Close method or a Dispose method.
The finalizers of two objects are not guaranteed to run in any specific order, even if one object refers to the other. That is, if Object A has a reference to Object B and both have finalizers, Object B might have already finalized when the finalizer of Object A starts.
The thread on which the finalizer is run is unspecified

There should be no reason you're calling finalize. Even though it's open to you for overriding, the best practice in using finalize is not to use them. Instead, inherit from IDisoposable. Not only is this a best practice, it doesn't interfere with garbage collection, and has the convenient ''using'' clause to auto dispose. Inheriting this class also notes to other developers that this is an object that has resources to dispose of, and I'm a particular manner. I even think the GC will call dispose during its garbage run.
In short, anything you can do with finalize is better done with dispose.

Related

Did rewriting Roslyn in C# make it slower? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I read this article: https://medium.com/microsoft-open-source-stories/how-microsoft-rewrote-its-c-compiler-in-c-and-made-it-open-source-4ebed5646f98
Since C# has a built in garbage collector, is Roslyn slower than the previous compiler which was written in C++? Did they perform any benchmarks?
Let me address a question that you didn't explicitly ask but applies to your question.
Question: Is explicit garbage collection faster than implicit garbage collection?
Answer: As you may already know C++/C uses explicit garbage collection which means that free() must be called to deallocate memory allocated on the heap. On the other hand, C# uses implicit garbage collection which means the memory on the heap is deallocated in the background. The key here is implicit garbage collection will deallocate memory when needed at optimal times while explicit will always deallocate each object individually(if done correctly). Implicit garbage collection achieves this by communicating with the OS and by using some other algorithms. In all, in most situations, implicit garbage collection will perform better than explicit due to the above explanation. For more info check out this post.
Answer To Your Question: Because I have not seen any bench marks myself, it is almost impossible to say if one would be faster than the other for sure. There are many other features than garbage collection which would effect the speed of each langauge implementation. To clarify, C# is a bytecode based language that uses the JIT(Just-In-Time) compiler. If I had to choose, I would choose the C++ implementation to be faster due to the JIT optimizations lacking in some cases compared to the C++ compiler. Again, when it comes to how fast these two languages will perform it will depend on the situation. For example, there are some optimizations that JIT can preform that are impossible to do with the C++ compiler.

How to handle unhandled exceptions at class-level [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have quite a large class that uses many more classes. It uses external resources (database, files etc.) and a few exceptions might happen.
As I learned, sometimes it is preferable to use the event of UnhandledException instead of putting try-catch blocks everywhere.
However, my class is just one of many other classes and the aforementioned solutions work at the application-level.
Can I somehow narrow it down to get fired only if the exception fired in this class and the other unhandled exceptions don't get caught?
Using AOP seems like a good way but I'm not sure.
I'm not sure if I entirely understand your question, but allow me to try to answer it anyway:
You're asking if it's possible to load your class in such a way that it knows which of the exceptions it might generate, are being handled in the class that's loading the dll? This seems impossible, simply because of the calling hierarchy. What I would suggest is that you document which exceptions may be thrown in your classes, using this mechanism:
/// <exception cref="ArgumentOutOfRangeException">Thrown if argument is greater than the size of the array.</exception>
That way your calling classes can be better prepared to handle the exceptions, and know more or less which possible exceptions aren't being handled.
Another approach is to encapsulate your code in try-catch blocks, and use the fact the more specific exceptions are handled first. You can then handle the scenarios you can resolve programmatically, and then catch the generic Exception last to ensure your program remains stable even if underlying classes fail catastrophically.
Unfortunately I don't see how you're going to tell your called dll, which of the exceptions it might throw are being handled.

Using IDisposable all the times is good? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I want to know suppose I create an object and then use
(IDisposable(object)).Dispose() after using that object.
Will this help me to improve my performance?Or should I wait for GarbageCollector to collect that object?
The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.
Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed
ref:
http://msdn.microsoft.com/en-us/library/system.idisposable(v=vs.110).aspx
A more detailed description
http://www.codeproject.com/Articles/413887/Understanding-and-Implementing-IDisposable-Interfa
Its purely depends on the context which we used, for example objects like DB connection objects usually needs to be disposed, any stream related operations needs to be disposed. It's not necessary to dispose every object which we create, most of them are handled by GC.

can dispose method clear manage code object? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
As garbage collection can't clear unmanaged code.To clear unmanaged code we use dispose method,but can vice versa possible?can we clear manage code object using dispose method?
A Dispose method implementation might set some fields to null, potentially making "child" objects eligible for garbage collection even if the containing object itself isn't eligible for garbage collection.
It can't forcibly delete objects though - the closest it could come would be to call GC.Collect.
Dispose certainly doesn't have to clear fields at all though - for example, with MemoryStream, you can access the data within the stream (via ToArray or GetBuffer) even after disposing of it.
Usually it's better (IMO) to just let the garbage collector get on with what it's good at.
If you really need to force this - you could implement IDisposable on your class and then use it within a using(){} block once it falls out of scope it will be cleaned up on the next GC.Collect cycle, which can be forced by calling the method.

Disposable resources in library code [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Imagine you're writing a library. Say, this library is going to be used in 24/7 server application. There are some unmaneged resourses, wrapped in your public API, so you implement Disposable pattern( you may even implement finalizers)
Normally, you would use using statement to free the unmanaged resources. But you are writing just a library, not a final application. What if another programmer 'forgotten' to call Dispose()? You are going to get resource leak in your lib!
We could rely on finalizers, but there is no guarantee that a finalizer would ever been called.
So, is there a way to guarantee that somehow the unmanaged resources would be freed? Any ideas?
There is no solution except documenting your classes. Write explicitly in your documentation how your classes are meant to be used (i.e. they are meant to be disposed at the earliest possible time, possibly with using, or with an explicit call to Dispose).
You are no more responsible for memory leaks if your consumer does not properly dispose its object than industrials are responsible for the pollution if people trash their garbage in the wild.
You could hope that the server application has code analysis rule CA2213: Disposable fields should be disposed enabled.
Otherwise I don't know if there is a way to guarantee that they call your Dispose() method.

Categories