Wednesday, October 10, 2012

The Dispose() method and the inheritance

Today I am going to write about the IDisposable interface – it’s Dispose() method, and how this should be really implemented in derived classes. The simplest implementation of Dispose() method will be just introduction of the following code to the class, and that’s all:
public class A : IDisposable
{    public void Dispose()
    {        // Disposal logic here 
    }
}
 
and this seems to be fine, but it is not.

Let’s assume for now that everything is fine, and we ship a library with the above code in it. Somebody, who is using the library, can easily use it in the following way:
public class B : A
{    public new void Dispose()
    {        //Class B specific dispose logic in here
        //And the following call is essential here

        base.Dispose();
    }
}

This seems to be fine as well, unless someone else, or even the owner of class B will use it in the following way:
using (A item = new B())
{    // some logic here
}

In this case, when exiting from the using block, the Dispose() method of type A will be called, which is sitting in the method table in memory as a separate record, and has nothing related to the Dispose() method of type B. And this will become a possible reason for a memory leak – any unmanaged resources introduced in class B will not be cleaned up !

One solution, of course will be to cast item to type B and call it’s Dispose() method explicitly, but that’s just complicating things, because this will need to be done in a finally block.

So let’s now see what I meant saying “it is not” in the beginning of the article, when was defining class A.

The thing is the the implementer of a public type must take the responsibility of problems like the one described by implementing types the way, so the users will not need to worry about the usage.

And the solution is actually simple – in every case, when introducing a type which implements the IDisposable interface, the Dispose() method must be marked either virtual (and the derived classes should override that method), or whole the class must be marked as sealed.

So by defining class A as sealed we will explicitly restrict its usage the way it was described – the incorrect usage. Now let’s see what will change, if we’ll mark the Dispose() method in class A as virtual and in class B override it.

Remember, this will force a single method record for a derived type to appear in the method table, so no matter how you’ll reference an instance of type B (either through type A, or any other type in the hierarchy) the Dispose method will call the Dispose method of type B, which, assumable (if implemented correct – as in the example above) will call the parent type’s Dispose() method and this will go by chain until the top of the hierarchy, making sure that any resource in whole the hierarchy got disposed.

Good luck with development !

Thursday, August 2, 2012

Synchronization: Working with synchronized resources

Today I'm going to write again about the synchronization, but will mainly concentrate on the way of helping to avoid some code duplication, and will save some time.

In one of my previous posts I've described several ways of synchronizing access to the resource, and what we’ve pointed out there as a general (of course with exceptions) practice each synchronized resource in needs to have an associated object, used for synchronizing access to that resource only, and for nothing else.

Thinking about that I came up with the following class definition which I found very handy:

public class ConcurrentResource<T>
{ 
  private readonly Object syncRoot = new Object(); 
  public readonly T Resource; 
  
  public ConcurrentResource(T argResource) 
  {
    if (argResource == null) 
    { 
      throw new ArgumentNullException("argResource"); 
    }
    
    this.Resource = argResource; 
  }
}



The ConcurrentResource type will encapsulate the object which to the access is going to be synchronized, and will also define internally a read-only property called syncRoot, which will be used for synchronizing the access.

Using that type I found it really handy but let me describe a bit more the use of it and what methods we can add to it to make it handier to work with.

So let's imagine we want to do some action with locking that resource. The following method will be really handy here, because it will encapsulate the locking mechanism in it as you can see:

public void HandleActionInSyncronizedContext(Action argAction)
{
  if(argAction == null)
  {
    throw new ArgumentNullException("argAction");
  }
 
  lock(this.syncRoot)
  {
    argAction();
  }
}



So the method internally will handle the locking mechanism and the caller will not need to use it directly in the code. One advantage of the abstraction, is that it will be very handy when we will need to switch from lock{…} to Monitor.Enter(…) call with timeout in one place, and get it working everywhere. There are bunch of interesting methods we can add to that type, and here are few of those:

public void WaitForPulse()
{
  Monitor.Wait(this.Resource);
}
 
public void Pulse()
{
  this.HandleActionInSyncronizedContext(()=>
  {
    Monitor.PulseAll(this.Resource);
  });
}
 



As a complete example of usage of the ConcurrentResource( of T) type you can take a look to the sources of ConsoleHoster project in here.

Sunday, July 22, 2012

Delegates and Events

Today I’d like to write about the events, but because I cannot talk about events without delegates, I’ll cover those as well in this post.
To make the article easier to understand (for new developers at least) let me describe a more real-world example so we’ll be able to model things from it. One such example can be the fire brigades' work – how they react to fires, how they being notified about fires and so on.
So thinking about it I assume that every fire brigade works for some kind of center, which control’s its work. And every such center has several brigades under its control. So let’s model that center as FireAlarmingCenter class described below:
public class FireAlarmingCenter
{
}

As we said earlier the FireAlarmingCenter will be one who notifies about fire alerts to the fire brigades. Before we will be able to add that notification capability to the FireAlarmingCenter class, we need to define what the notification will look like. and here where the delegates come in. To specify the details about the specifics of the notification we need to describe those through a delegate, which will define a signature of a method it can reference to, or a method, which can be used as a handler for an event of that delegate type.

public delegate void FireAlarmEventHandler(FireAlarmingCenter argCenter, AlarmDetails argDetails);

Now let’s add the event definition to the FireAlarmingCenter type as follows:

public event FireAlarmEventHandler FireAlarm;

Great, now we have the FireAlarmingCenter type, so let's see how this event is going to be consumed.
As we have said already, the consumers of FireAlarm event will be the fire brigades, which we can model like this:

public class FireBrigade
{
    public FireBrigade(FireAlarmingCenter argCenter)
    {
        if (argCenter == null)
            throw new ArgumentNullException("argCenter");

        this.Center = argCenter;
    }

    public FireAlarmingCenter Center
    {
        get;
        private set;
    }
} 

Now we’ve created the base plumbing so the FireBrigade will have the reference to the FireAlarmingCenter it’s “working for”. But there is still a hole there – the FIreBrigade doesn’t somehow “listen” to the FireAlarm event of its center. To do so, we just need to aappend the following line to the FireBrigade class constructor:

this.Center.FireAlarm += new FireAlarmEventHandler(this.HandleFireAlarm);

Although the C# 4.0 language let’s the developers to skip the delegate type after += operation, when registering for events and specify only the method name, which is going to work as handler for that event, I like that style, so its really visible from code what type exactly the event is, so to the handler method signature is. So that line will assume that we’ve defined the “HandleFireAlarm” method already in the FireBrigade class, which will contain logic about what to do in case of a fire.
Now let's see how the FireAlarmingCenter will notify the FireBrigade-s about a fire. I’m not going to write or guess what the conditions are on when to notify it, but am really going to concentrate on how it will be fired. The most simple way to do that is as follows:
  
private void OnFireAlarm(AlarmDetails argDetails)
{
    if (this.FireAlarm != null)
    {
        this.FireAlarm(this, argDetails);
    }
}

Very nice and simple, it’s really not what we want. So let’s go and see what is happening behind those lines ?
So the first line in the method checks whether there are any listeners registered for the FireAlarm event or not. Next, if there are listeners to the FireAlarm event, the most important thing is going to happen – the event is going to be called. To answer the question – “what means an event is called?”, I’ll need to go back a bit to describe what the delegate is.
So the delegate is a reference of a method, but not only – it is actually a list of references to methods, which all are matching the signature of the delegate. Actually, the definition of the delegate we’ve created is being translated by the compiler to a class definition with the name of that delegate and deriving from an abstract class called “MulticastDelegate”:
 
public class FireAlarmEventHandler : MulticastDelegate
{
}

So now we can approach to an event as a field of a specified delegate type in a class it’s defined in. So when in the FireBrigade class’s constructor the += operation on the FireAlarm event is being called, it actually adds a new method reference (which is specified on the right from the += operator) to the delegate invocation list.
Now, when the event (in this case the FireAlarm) is being called, the following happens:An iterator is being created which iterates over all the registered methods to that delegate instance, and each element of that iterator (in this case a method reference) the method is being called with parameters passed in to the event call. But this seems to contain a problem.Imagine a situation when during the event listeneres execution (iterating over the list of handler methods) a new FireBrigade will be constructed for that FireAlarmingCenter – the invocation list will be modified so an exception will be thrown here.But don’t worry – there is a very handy way of handling this and I really like it. If we’ll modify the code like this:

private void OnFireAlarm(AlarmDetails argDetails)
{
    FireAlarmEventHandler tmpEvent = this.FireAlarm;
    if (tmpEvent != null)
    {
        tmpEvent(this, argDetails);
    }
}

on the first line in the method the invokation list of the delegate will be copied and the next operations will be working on the copied list including the invocation itself) so adding or removing any new handlers to the FireAlarm event won’t affect the invocation any more. This technique is usually referenced as “Event Invoke Pattern”.
Visual Studio has a very nice snippet for this: “invoke”. Just type invoke in VS.Net and hit Tab twice (Tab+Tab) and you’ll get the code automatically appear in your source.

So I think that’s all for this post. Good luck with your development.

Sunday, July 15, 2012

The ConsoleHoster app

Hi.

The recent 4-5 months I was working on a very interesting project which will most probably be a help for other developers. Feeling quite good about it I finally decided to make it open source.
So here is the link where it's published: http://consolehoster.codeplex.com/
Hope you'll like it, and please leave your feedback there and join me in developing it, if you're intersted.
In my future posts I'll try to cover it in more details.

Regards,
Artak

Sunday, July 8, 2012

Regex: Identifying paths

Hi again and thank you for visiting my blog.

It's already three months I'm working on a project which again, as many other projects I'm working/worked on, started from just an idea.
So one of the challenges I met in this project was to come up with a regular expression, which will identify whether the given part of the string is a path, part of it, or relative one.
Remember (or if you don't know try) the TAB support in windows command window - you can type in a relative or full path, then type some prefix and on each sequentiall hit of TAB button, the file/folder names, which are in the specified path and start with the typed prefix, will be placed like auto-completition feature one after another.
So I finally came up with the following regular expressoin:
"((((^\w:|\s\w:)|\.\.?)(\/|\\))?(([\w.]+( [\w.]+)?)(\/|\\))*)|((((^\w:|\s\w:)|\.\.?)(\/|\\))?(([\w.]+([\w.]+)?)(\/|\\))*))([\w\.]*)\t"
Because it's quite complex, the processing was really taking long. First I tried to compile that regular expression into a separate assembly and then use the compiled one, but unfortunately it affected the performance harder, than earlier. Eventually I understood that I don't need all the groups defined in the pattern, so I removed those (marked those not to be counted as groups using (?:...)), and it increased the performance really good. So here what I ended up with:

"(?:(?:(?:(^\w:|\s\w:)|\.\.?)(?:\/|\\))?(?:(?:[\w.]+(?: [\w.]+)?)(?:\/|\\))*)|(?:(?:(?:(^\w:|\s\w:)|\.\.?)(?:\/|\\))?(?:(?:[\w.]+(?:[\w.]+)?)(?:\/|\\))*))([\w\.]*)\t"Althought the compiled query execution time need to be shorter than the non compiled one, I haven't went into details why it was like that, but the fact is fact - that's true. I'm pretty sure that for shorter regular expressions that will work faster, but no in this case.

Hope the regex will be helpful.

Enjoy .Net Development !!!

Monday, April 9, 2012

Syncronization: deadlocks and how to identify those

These days synchronization become very actual problem for any developer - nowdays its really hard to even imagine a single threaded application. Of course with this, some headache arises with deadlocks. Usually developers use lock(...) { } statement to synchronize access to some code block, and that is one possible reason of a deadlock. Don't get me wrong - I don't say that if you use lock statement, then you have a deadlock, but what I say, is that if you have a deadlock - then its definitely happening on one of the lock statements you've used in your code. So what to do to avoid those ? Or actually, which will be more correct to say, how to identify the lock statement where the thread blocks causing a deadlock forever ?
Fortunately, as almost always, there is a very handy option under the hand - The Monitor class. You probably know, that the lock (obj){...} statements translates to the following code:
try
{
    Monitor.Enter(obj);
    // ...
}
finally
{
    Montior.Exit(obj);
}
To make this code "deadlock-proof", you need to replace the Monitor.Enter method call as follows:
try
{
    if(!Monitor.TryEnter(obj, TimeSpan.FromSeconds(2))
    {
        // Log deadlock reason in here
        throw new Exception("Unable to take exclusive lock on the given object");
    }
    // ...
}
finally
{
    Montior.Exit(obj);
}

Here we are passing a TimeStamp parameter to the TryEnter method, specifying the amount of time to wait for the lock. So if during the specified time period it is impossible to take lock over the specified object, then the method will return false, and we'll be able to log something, which will tell us the place in code where the actual deadlock is happening. Of course it's not so convenient to use whole this construct in code, so this can be extracted to an extension method like the following:

public static void SyncronizeCallByLocking(this Action argAction, object argLock)
{
  // Argument validation in here
  if (!Monitor.TryEnter(argLock, TimeSpan.FromSeconds(2000)))
  {
    // Log exception in here, if required
    throw new ApplicationException("Unable to lock the object");
  }
 
  try
  {
    argAction();
  }
  finally
  {
    Monitor.Exit(argLock);
  }
}

After this it's really easy to wrap the code block, which needs to be synchronized like this:
new Action(()=>
  {
    // Code which needs to be syncronized
  }).SyncronizeCallByLocking(objectToLock);

By using this technique you will definitely not waste many hours of struggling by trying to find the deadlock reasons in your application, and guessing where those can arise from. Of course, if you want after fixing all the issues you're free to convert back to using the lock statement instead of what was described, but I won't bother about it, because you don't know what changes may come later, and how those may affect your application.
Good luck with your development.

Tuesday, March 27, 2012

Reading redirected output of the process: limitations and how to work around

During last month I was working on a project built on top of the Console-windows. An interesting problem I was facing is the read of redirected output (asyncronous) from that process. It seems to be quite easy to handle such a task, and it is, unless you need to read "all the output".
Well, the simple approach of handling such a task is like the following:
1. Define a ProcessStartInfo with redirected output:
    ProcessStartInfo tmpStartInfo = new ProcessStartInfo()
    {
        FileName = "consoleApp.exe",
        UseShellExecute = false,
        RedirectStandardOutput = true
    }
2. Create a process and set the start info to alrelady defined one:
    ProcessStartInfo tmpProcess = new Process()
    tmpProcess.StartInfo = tmpStartInfo;
3. Define and register a handler for the OutputDataReceived event:
    private static void Process_OutputDataReceived(object sendingProcess, DataReceivedEventArgs outLine)
    {
        Console.WriteLine(outLine);
    }
    tmpProcess.OutputDataReceived += new DataReceivedEventHandler (Process_OutputDataReceived);

4. Start the process.
    tmpProcess.Start();

Yes, it's simple, but there is an open issue left in here. The process won't redirect the output, until there is a new-line character in the stream, which means, that the Process will fire the OutputDataReceived event only as soon as a new line is available on the stream. So for me this was a big limitation, because if the process is writing something on a line and still waits for some input from the user on the same line, we will never receive that line, and won't even know that the process is waiting for user input there.
To fix this we need to observe the stream on our own, not awaiting the event to fire. So, here is the algorithm I came up with, to handle the behavior described:
   
private void ObserveStreamInBackground()
{
  try
  {
    char? tmpStreamChar = null;
    do
    {
      int tmpStatus = this.Stream.Peek();
      if (tmpStatus == -1)
      {
        if (this.messageBuffer.Length > 0)
        {
          this.InformMessage();
        }
        tmpStreamChar = (char)this.Stream.Read();
      }
      char tmpCurrentChar = tmpStreamChar ?? (char)this.Stream.Read();
      if (tmpStreamChar.HasValue)
      {
        tmpStreamChar = null;
      }
      this.messageBuffer.Append(tmpCurrentChar);
      if (tmpCurrentChar == '\n')
      {
        this.InformMessage();
      }
    } while (true);
   }
  catch (ThreadAbortException ex)
  {
  }
}

private void InformMessage()
{
  string tmpMessage = this.messageBuffer.ToString();
  this.messageBuffer.Clear();
  this.lastMessage = tmpMessage;
  this.lastMessageReceivedAt = DateTime.Now;
  this.OnMessageReceived(tmpMessage);
}

The InformMessage() method is there to just clear the current message buffer and fire the event with the message data in it.
That's all. Experiment with it and give me your feedback. Good Luck !

Friday, March 9, 2012

Reflection: working with generic types


An interesting problem I was facing during last few days drives me to write this post. The problem was to create a generic type instance (let's say List), the type parameter for which is known only during runtime. Let's examine the following code fragment:
Type genericListOfInt = typeof(List<int>);
Type genericListOfString = typeof(List<string>);
bool sameType = genericListOfInt == genericListOfString;
//sameType is false here, so those Types are differenet
Both the variables seems to be instances of the same List (List of T) type, but because the T type parameter is different the compiler will generate two different classes for List and List so the variables will not be equal. But how to handle the problem we do face ?
Examining the System.Type class we will find out a very interesting method called:GetGenericTypeDefinition() method. This method returns a Type object, representing the generic type definition, from which the type, which for the method was called, was constructed, so actually the type, which can be used to construct other Generic types as well.
So modifying the code above will give us the following:
Type genericListOfInt = typeof(List<int>);
Type genericListOfString = typeof(List<string>);

bool sameType = genericListOfInt == genericListOfString;
//sameType variable is true now, so both variables are referencing the same Type instance
Apparently, the type, which is reffered by both genericListOfInt and genericListOfString variables can be accessed with the following variable as well:
Type genericList = typeof(List<>);
This makes it really handy, so we don't want the compiler to generate any classed which are actually useless just to get the reference to a generic type.
Now this type can be used to construct different Lists for different types dynamically (List<[any type you want here]>). So here is a simple code for constructing a list of the given type:
public static object CreateGenericList(Type ofType)
{
  Type genericListType = typeof(List<>);
  return Activator.CreateInstance(genericListType.MakeGenericType(new Type[]{ofType}));
}
Please note also, that the List type was taken for example only, so to access multi-type based generic type (like KeyValuePair<k,v>) you can easily use the same technique:
Type genericKVPair = typeof(KeyValuePair<,>);
Now, the last scenario left to discuss, is how to dynamically identify the generic type parameters a type has (string in case of List and (int, string) in case of KeyValuePair)? The Type class defines another interesting method called GetGenericArguments(), which returns an Array of Type objects. Combining this method with MakeGenericType will let us write the following code, which is used to build a KeyValuePair of Types, which are the switch from the original one by type parameter places (for KeyValuePair it will return KeyValuePair):
public object CreateInstnaceOfTheSameType(object original)
{
  if (original == null)
  {
    return null;
  }

  Type origType = original.GetType();
  if (!origType.IsGenericType || origType.GetGenericTypeDefinition() != typeof(KeyValuePair<,>)
  {
    throw new ArgumentException("KeyValuePairs expected");
  }

  Type[] typeArgs = origType.GetGenericArguments();
  Type typeToConstruct = origType.GetGenericTypeDefinition().MakeGenericType(new Type[] { typeArgs[1], typeArgs[0]});
  object[] constructorParams;
  // I'm skipping the code for constructorParams initialization, cause it's out of scope
  return Activator.CreateInstance(typeToConstruct, constructorParams);
}
Hope you will find this post helpful.

Regards...

Saturday, February 18, 2012

Syncronization with lock() - bad habits

Hi all.

Today I wanted to touch the lock statement in C#, and how many developers used to use it. There are a lot of books on C#, where authors bring examples like the following:
public class LibraryType
{
  public void X()
  {
    lock (this)
    {
      // some actions
    }
  }
}
I'd like to touch this because many developers are using the same technique of syncronizing access to a shared resource. There is nothing wrong in such a code, but there is a potential problem hidden in it.
What if somebody, who is going to use the library (which contains above written code) will decide to syncronize access to some shared resource using an instnace of a type, which contains above shown method X()?
In single threaded application there will be no problems at all, but in case of multithreaded applicaiton, the caller will face a deadlock. Take a look to the following code example:
// This code is in different assembly
internal class WrapperClass
{
  private LibraryType libTypeInstance = new LibraryType();

  private void XCaller()
  {
    lock(this.libTypeInstance)
    {
      Thread tmpThread = new Thread(new ThreadStart(()=>this.libTypeInstance.X()));
      tmpThread.Start();
      tmpThread.Join();
    }
  }
}
The thread which is calling the method XCaller() will lock the libTypeInstance object, and then will create another Thread inside, which will try to lock the same object instnace from the inner X() method. So that thread will wait untill the object is not unlocked, but for this to happen that thread should finish its job. So the application will halt here.
So the prefered technique in syncronization scenarios will be to keep a private instancec of an Object type and lock that instance, instead of locking the object (this). This will result in the following change in the code:
public class LibraryType
{
  private Object syncObject = new Object();

  public void X()
  {
    lock (this.syncObject)
    {
      // some actions
    }
  }
}

After the following change the above mentioned example will work with no problems.

Thanks for reading.

Sunday, January 29, 2012

AppDomains - Why and How ?

Finally I've found time for this post, which I was planning last year already.
So, where you may need an AppDomain in your application, how you'll treat it and what are the benefits of using it? I'll try to answer to those question. Read further.
Let's start from the theory: An Application Domain represents an isolated environment in a managed .net application process. Saying roughly those are sub-process layers, where the code will execute. The important features of Applicaiton Domains I'd like to mention here are the following:
1. An applicaiton domain has its own - isolated from others, memory
2. Those can be loaded and unloaded dynamically. Unloading an applicaiton domain will unload all the assemblies loaded in that applicaiton domain (there are still some cases when this is not true, although non-practical cases).
Now let's try to find a usage. Imagine a scenario, where the applicaiton needs to load a component from non-trusted source. There are several issues with this, and the most important for me are Security and Reliability.
Security: you never know what the code in that component is doing behind the scenes.
Reliability: the component can be non-well designed, leaving holes for exceptions to arise.
Let's first concentrate on the case, if we are going to handle such scenario without application domains. Of course for interaction with that third-party component there will be a well-defined interface, and every call of a method of that interface (actually an instnace of 3-rd party component, which I will call Component X further) will be wrapped in a try-catch block. But what if the component does something else behind the scenes ? For example it can has a background thread which does some other processing. In this case, your handlers won't be able to handle exceptions coming from that background processed code, because those are not on the stack of a thread you've just called a method in. So what will happen ? I won't go into details here, but will say that an exception coming out from such backgroun thread (which is not properly caught in Component X, will finally take your process down, and you'll have no chance to react, cause have no handlers at all.
Don't blame me here, cause I'm not going into some special cases here, like WinForms, where you can handle all the exceptions on the Application level by registering to ThreadException event.
On the reliability side - you don't know what the code is doing from data-accessing perspective. So there are limited choices for you to react here - limit your own application permissions to not allow the Component X to do something wrong. But still, you will share the same address space in memory with that component.
Ok, now let's jump to the usage of application domains for this scenario, and see how those will solve the above mentioned problems.
First, in FCL (Framework Class Library) there is a type called AppDomain, which is handling management and interaction with application domains. So let me from now on call application domains just AppDomain for the sake of simplicity only.
Well, the proper design for the above scenario will be the following:
1. Create an AppDomain

AppDomain tmpDomain = AppDomain.CreateDomain("ComponentX Domain");

2. Register for the UnhandledException event of that AppDomain

tmpDomain.UnhandledException += new UnhandledExceptionEventHandler(OnComponentDomain_UnhandledException);

3. Add proper permissions to that AppDomain (this is called sandboxing - limiting permissions)
// Leaving code for this section, because this is out of scope from this article
4. Load the Component X assembly into that AppDomain

Assembly tmpComponentAssembly = tmpDomain.Load(AssemblyName.GetAssemblyName("./ComponentX.dll"));

5. Create Component X instance in that AppDomain.
6. Create a proxy in our AppDomain to interact with Component X instance in the new-created domain(because the memory of each AppDomain is isolated, the process of passing data between AppDomain-s involves serialization and deserialization of that data, and whole the process is refered as Marshalling).

Type tmpComponentType = GetComponentTypeFromAssembly(tmpComponentAssembly, typeof(IComponentContract).Name);
IComponentContract tmpComponentProxy = tmpDomain.CreateInstanceAndUnwrap(tmpComponentAssembly.FullName, tmpComponentType.FullName) as IComponentContract;

7. After finishing working with Component X unload AppDomain of Component X to free up memory. This will also unload the assembly loaded in that AppDomain.

// This call is missing in the example solution attached to this article.
tmpDomain.Unload();

Great, this solves the security problem and what about the reliability? The AppDomain type (in Net Framework 4.0) defines an event called UnhandledException. Unfortunately there is no way to handle that exception and continue the normal flow of the application, but the good thing here is that you get your "last-chance" to save state, or log the exception, and even schedule a task in OS to start a new instance of your application. There are several important aspects you should be aware of regarding this event: "This event can be handled in any Applicaiton Domain, although its not necessarily raised in the application domain, where the exception occured. An exception is unhandled only if the entire stack for the thread has been unwound without finding an applicable exception handler, so the first place the event can be raised is in the application domain where the thread originated.
If the UnhandledException event is handled in the default application domain, it is raised there for any unhandled exception in any thread, no matter what application domain the thread started in. If the thread started in an application domain that has an event handler for UnhandledException, the event is raised in that application domain. If that application domain is not the default application domain, and there is also an event handler in the default application domain, the event is raised in both application domains."
The quoted part I've taken from MSDN documentation cause it very well explains that event propogation. I still recommend you to read the MSDN page.
In the section above I've specified the exact version of Net Framework because in the earlier versions the behavior was slightly different. Here is another section from MSDN for earlier versions: "In the .NET Framework versions 1.0 and 1.1, an unhandled exception that occurs in a thread other than the main application thread is caught by the runtime and therefore does not cause the application to terminate. Thus, it is possible for the UnhandledException event to be raised without the application terminating. Starting with the .NET Framework version 2.0, this backstop for unhandled exceptions in child threads was removed, because the cumulative effect of such silent failures included performance degradation, corrupted data, and lockups, all of which were difficult to debug."
I've also created a small solution with code representing the scenario described in this article. Click here to download the example codes.

Friday, January 27, 2012

Comparing IPAddress-es

Recently I was struggling with a LINQ expression, where I had a comparison of two ip addresses. Like used to - the comparison was done by the == operator, which was the cause of the headache.
NEVER USE == WITH IPAddress.
Seems IPAddress have no its own overrie for ==, and because it's a reference type that operator is just comparing two addresses(whether those point to the same location in memory or not). And I was getting false for equal ip address comparison.
You can just try to do the following:

bool areEqual = IPAddress.Parse("150.148.1.54") == IPAddress.Parse("150.148.1.54");
// the areEqual now is false

So the proper way to compare them is to use the Equals method, which IPAddress type has an override for:

bool areEqual = IPAddress.Parse("150.148.1.54").Equals(IPAddress.Parse("150.148.1.54"));
// and now the areEqual will be true


Good luck with your coding.