Would someone explain the following C# code a little bit for me?
I do have knowledge of the normal usage of IDisposable. But I don't understand the following code. The instantiate of new LogLog.LogReceivedAdapter(configurationMessages) looks like have nothing to do with the code block within keyword using. How does statement InternalConfigure(repository, configFile) eventually update variable configurationMessages?
BTW, the code piece was grabbed from log4net XmlConfigurator.cs#508
static public ICollection Configure(ILoggerRepository repository, FileInfo configFile)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository, configFile);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
I do not know that exact code, but it may look like the following:
LogLog registers configurationMessages in some static class (let's call it Log) upon construction;
InternalConfigure uses that static class (and in effect configurationMessages are filled up)
The Dispose() method of LogLog class removes the adapter from the Log class.
The part you presented requires heavy guessing, but I believe, that this is the case.
I believe the constructor of LogReceivedAdapter is an answer.
public LogReceivedAdapter(IList items)
{
this.items = items;
handler = new LogReceivedEventHandler(LogLog_LogReceived);
LogReceived += handler;
}
As you can see it does some magic behind, thus - even though there's no direct reference to newly created instance in your code - it might have some sense :)
C# treats classes that implement IDisposable in one specific way: it calls Dispose() at the moment when the code reaches the closing bracket of the "using" block where the object was created.
Look at Dispose() method of the LogLog.LogReceivedAdapter. The code ensures, that this method is called.
Related
What is the best way to initialize static fields via a static init method and afterwards make sure that the method is never called again? (no more than once during the lifetime of the program)
This is an example of what I currently thought of, it seems pretty simple to me but I couldn't find any examples of similar patterns that deal with this:
class Entity
{
static Manager manager;
static bool isInitialized;
public static void Initialize(Manager manager)
{
if (isInitialized)
throw Exception("Class Entity already initialized."
+ "Do not call Entity.Initialize() twice.");
isInitialized = true;
Entity.manager = manager;
}
}
What is the best way to initialize static fields via a static init method and afterwards make sure that the method is never called again?
Do you really have to do this? Why do you not want to create an instance of Manager and make it available to code which relies on it through dependency injection? That would make your code much cleaner:
You'd allow it to be testable with different initialization paths
You wouldn't need any checking for "bad" duplicate initialization
You wouldn't need to structure your calling code to specify a single initialization point for this class. (You may need to do something similar for the IoC container of course...)
You'd allow your code which depends on it to be more testable too
The code which depends on Manager would be express that dependency in a clearer way
I suspect you haven't found any similar examples because it's an anti-pattern.
If you do go for your current approach, you should really try to make it thread-safe, too...
Don't over think it, if that pattern works for you, go with it. There isn't always a "right" answer, and trying to stick to rigid patterns and practices just for the sake of sticking to them is not a good idea either. IMHO.
Sorry for stating the obvious, but you could use the object initializer or the static constructor. Besides that, you can just not call the method. Seriously. Why would someone call a method called initialize anyway.
What you could do is this. You can hide the method from IntelliSense and similar with this attribute. Stops it from cluttering up the dropdown too
Your implementation is not thread-safe, but is otherwise reasonable. If it's intended for use in a multithreaded environment, add locking.
In your sample, the open question is what should happen if multiple callers (possibly from multiple threads) call the initialization method with different parameters. This is what makes your pattern unusual, and prevents you from using the obvious static constructor or object initializer.
Can't you just use a static constructor?
Of course, you do not have control over when this constructor is called, but don't know if this is a requirement.
http://msdn.microsoft.com/en-us/library/k9x6w0hc(v=vs.80).aspx
You might want to use a singleton pattern with parameters to only expose certain functionality of the Manager variable.
class Entity
{
private Manager _manager = null;
public Manager manager
{
get
{
return _manager;
}
set
{
if (manager == null)
{
_manager = value;
}
}
}
/* rest of class */
}
Now you can use the manager object as any variable, but repeated sets will not modify the value.
this.manager = new Manager(0); // sets the manager
this.manager = new Manager(1); // does nothing
Now to complete the pattern in your constructor somewhere or at some reset function you might want to do a
this._manager = null;
I have a quite large project which I try to keep as clean and tidy as possible. When I run the code analyzer in Visual Studio I get a reliability error which I find quite annoying. I'd really like to learn how to work around it. Here is a simplified example of what I am doing.
Here is the warning.
Warning 1 CA2000 : Microsoft.Reliability : In method 'MyExampleClassForStackOverflow.AddFeed(string)', call System.IDisposable.Dispose on object 'new FeedClassExamle()' before all references to it are out of scope.
Here is my example code:
class MyExampleClassForStackOverflow : IDisposable
{
public ConcurrentDictionary<string, FeedClassExamle> Feeds { get; set; }
public void AddFeed(string id)
{
//The warning is coming from this code block.
//In the full code, the feed classes collects data on a specific
//interval and feeds them back using events.
//I have a bunch of them and they need to be accessible so I
//store them in dictionaries using keys to effeciently find them.
Feeds.TryAdd(id, new FeedClassExamle());
Feeds[id].Start();
}
public void Dispose()
{
foreach (var item in Feeds)
item.Value.Dispose();
}
}
class FeedClassExamle : IDisposable
{
public void Start()
{
}
public void Dispose()
{
}
}
In order to test the code, use:
using (var example = new MyExampleClassForStackOverflow())
{
}
Any suggestion would be welcome.
The warning exists because the code analysis tools can't determine whether the object will get disposed correctly. The way your code is written, the object will not in fact get disposed correctly, but fixing the code will likely not eliminate the warning.
Fundamentally, what needs to happen is for every the AddFeed method to ensure that something will call Dispose on every FeedClassExample instance it creates. The best approach is to avoid creating a FeedClassExample instance if one already exists in the dictonary under the present ID. Failing that, the AddFeed method should either dispose of any FeedClassExample it creates but then decides not to store in the dictionary, or else swap with the one that is in the dictionary (I'm not sure what methods ConcurrentDictionary supports to do that) and then Dispose the old one. The essential requirement is that at all times outside the actual execution of AddFeed, the dictionary will hold all instances of FeedClassExample that have been created but not destroyed.
It may be informative to add a destructor in your FeedClassExample class which does nothing except log a message. If you are calling Dispose on that class correctly, the destructor will never execute. If you fail to call Dispose, it will. Thus, if the destructor ever executes, you can know you're doing something wrong.
The object isn't getting Disposed of if TryAdd fails, so try doing this explicitly:
public void AddFeed(string id)
{
FeedClassExample fce = new FeedClassExamle();
if (!Feeds.TryAdd(id, fce))
{
fce.Dispose();
}
Feeds[id].Start();
}
Only create the instance if it needs to be added:
if (!Feeds.ContainsKey(id)) {
Feeds.GetOrAdd(id, new FeedClassExamle());
}
I have code similar to the following, should I explicity dispose of the listener object in the following code?
i.e should this code:
foreach (System.Diagnostics.TraceListener listener in localObj.Listeners)
listener.WriteLine("some logging");
be re-written as:
foreach (System.Diagnostics.TraceListener listener in localObj.Listeners)
{
listener.WriteLine("some logging");
listener.Dispose();
}
reasons for either way of coding would be appreciated.
In the above code, you are just accessing a reference to each TraceListener and calling the WriteLine() Method and there is no need to call Dispose() in this scenario.
Sorry, I would like to comment on the ChrisBint answers, but I couldn't. In brief, I agree with ChrisBint, you should not call Dispose in the above-mentioned scenario:
TraceListeners belong to localObj, and it is responsibility of the localObj to rule the lifetime of its inetrnal objects. Therefore the second piece of code seems odd enough.
If you implement getter of localObj.Listeners with generation of new collection and do not expose real internals of the localObj, you needn't explicitly call Dispose, it will be called by the GarbageCollector.
The msdn documentation of the System.IDisposable interface states that
The primary use of this interface is to release unmanaged resources.
I'm wondering what are alternative uses.
For example we also needed the IDisposable interface for other allocated resources, such as event subscription and so.
We used the interface as a marker to allow a class instance to know when it's no more used from clients. Client and infrastructural code explicitly call IDisposable.Dispose() whenever they no more need a logical instance of a class implementing the code.
There's no relation with unmanaged resources wrapped from the interface.
When we choosed the IDisposable interface for such a behaviour we considered it as an alternative (undocumented) use of the interface.
Which are the alternative use of IDisposable you have found?
Are they legittimate? Is the MSDN documentation wrong?
I think your reading of the documentation is wrong. Saying that any usage of IDisposable that is not related to unmanaged resources is undocumented is a bit like saying that any usage of System.Int32 that is not counting things is undocumented. It is an interface and has no implementation, there is no functionality there to even begin distinguishing between what's documented and what's undocumented.
The purpose of IDisposable is simply to provide the developer with a mechanism to deterministically control the lifetime of their objects. It just so happens that this mainly a requirement for dealing with unmanaged resources.
One of the more fancy uses of IDisposable is the using block syntactic sugar. As others have mentioned, using blocks give an operation scope and I think those are quite elegant.
Example 1 - timing blocks
StackOverflow uses mini profiler that uses using blocks to identify nested regions of execution:
using (profiler.Step("Doing complex stuff"))
{
using (profiler.Step("Step A"))
{ // something more interesting here
Thread.Sleep(100);
}
using (profiler.Step("Step B"))
{ // and here
Thread.Sleep(250);
}
}
The alternative to not using using is pretty horrible and I don't even want to mock it up here.
Example 2 - Disposable action
There have been different variations of disposable action pattern making rounds in .NET Domain Driven Design circles. Ayende has one, so does Udi Dahan in his Domain Events implementation, Jimmmy Bogard has a slightly different take on this, still in the context of Domain Events. The crux of the pattern is that you want to perform certain actions in some context, then have the context revert back to what it was before after you are done.
Ayende provides a simple example:
class UsuallyReadOnly {
//.. implementation
public IDisposable AllowModification
{
get
{
_allowModification = true;
return new DisposableAction(()=>{ _allowModification = false; } );
}
}
}
And UsuallyReadOnly's usage:
UsuallyReadOnly foo = new UsuallyReadOnly();
using(foo.AllowModification)
{
foo.Name = "Bar";
}
IDisposable is often used in conjunction with using to activate and deactivate something in a definite scope even if it is not an unmanaged resource. The use you describes sound as a reference counting and for sure is not recommended.
For "resources", substitute "responsibilities". When an object is said to hold an unmanaged resource, what that really means is that there is some task that needs to get done sometime, and the object is the only thing with the information and impetus necessary to do it. The purpose of "Dispose" isn't to get rid of any tangible entity, but rather to allow an object to "put its affairs in order". Someone is putting his affairs in order before his death isn't doing anything to himself, but rather he is ensuring that the things he has to do to persons and things outside himself get done. Likewise with IDisposable.Dispose.
Remember there is also the using pattern which acts a bit like RAII.
using ( DisposableObject obj = new DisposableObject( ) )
{
.....
}
So Dispose gets called when the using block is exited.
One of the more popular uses of the IDisposable interface is transaction scopes. You can use it to wrap some SQL logic in a transaction, and explicitly call Complete() to end the transaction:
using (var scope = new TransactionScope())
{
using (var connection = new SqlConnection(connectString))
{
// perform sql logic
...
scope.Complete();
}
}
You could also use a similar pattern for just about anything that requires a temporary function, such as creating and deleting a temporary file:
public class TempFileProvider : IDisposable
{
public Filename { get; private set; }
public TempFileProvider()
{
Filename = Path.GetTempFileName();
}
public void Dispose()
{
File.Delete(Filename);
}
}
So you could use it like:
using (var tempFileProvider = new TempFileProvider())
{
DoSomethingWithFile(tempFileProvider.Filename);
} // deletes temp file
Have a look at the following question Need an alternative to my IDisposable Hack
There i give a nice example of what i used IDisposable for. :)
Granted, it is not the ideal solution, however, it helped me a lot.
i'm working on a fork of the Divan CouchDB library, and ran into a need to set some configuration parameters on the httpwebrequest that's used behind the scenes. At first i started threading the parameters through all the layers of constructors and method calls involved, but then decided - why not pass in a configuration delegate?
so in a more generic scenario,
given :
class Foo {
private parm1, parm2, ... , parmN
public Foo(parm1, parm2, ... , parmN) {
this.parm1 = parm1;
this.parm2 = parm2;
...
this.parmN = parmN;
}
public Bar DoWork() {
var r = new externallyKnownResource();
r.parm1 = parm1;
r.parm2 = parm2;
...
r.parmN = parmN;
r.doStuff();
}
}
do:
class Foo {
private Action<externallyKnownResource> configurator;
public Foo(Action<externallyKnownResource> configurator) {
this.configurator = configurator;
}
public Bar DoWork() {
var r = new externallyKnownResource();
configurator(r);
r.doStuff();
}
}
the latter seems a lot cleaner to me, but it does expose to the outside world that class Foo uses externallyKnownResource
thoughts?
This can lead to cleaner looking code, but has a huge disadvantage.
If you use a delegate for your configuration, you lose a lot of control over how the objects get configured. The problem is that the delegate can do anything - you can't control what happens here. You're letting a third party run arbitrary code inside of your constructors, and trusting them to do the "right thing." This usually means you end up having to write a lot of code to make sure that everything was setup properly by the delegate, or you can wind up with very brittle, easy to break classes.
It becomes much more difficult to verify that the delegate properly sets up each requirement, especially as you go deeper into the tree. Usually, the verification code ends up much messier than the original code would have been, passing parameters through the hierarchy.
I may be missing something here, but it seems like a big disadvantage to create the externallyKnownResource object down in DoWork(). This precludes easy substitution of an alternate implementation.
Why not:
public Bar DoWork( IExternallyKnownResource r ) { ... }
IMO, you're best off accepting a configuration object as a single parameter to your Foo constructor, rather than a dozen (or so) separate parameters.
Edit:
there's no one-size-fits-all solution, no. but the question is fairly simple. i'm writing something that consumes an externally known entity (httpwebrequest) that's already self-validating and has a ton of potentially necessary parameters. my options, really, are to re-create almost all of the configuration parameters this has, and shuttle them in every time, or put the onus on the consumer to configure it as they see fit. – kolosy
The problem with your request is that in general it is poor class design to make the user of the class configure an external resource, even if it's a well-known or commonly used resource. It is better class design to have your class hide all of that from the user of your class. That means more work in your class, yes, passing configuration information to your external resource, but that's the point of having a separate class. Otherwise why not just have the caller of your class do all the work on your external resource? Why bother with a separate class in the first place?
Now, if this is an internal class doing some simple utility work for another class that you will always control, then you're fine. But don't expose this type of paradigm publicly.