• Code
  • Tags
  • Users
  • Titles
  • Log in
  • Feedback
  • FAQ
Share Code
Welcome to ForkCan.com

ForkCan is all about sharing code in a social way.

Discuss, debate or argue with other devs about their or your own code.

Give other devs feedback or make a Fork (Make a better version of a shared code).

Rate the code, if you use the code mark it as used so others can see if the shared code is used by someone.

Help each other to be better devs and to be more productive.


Features not working yet:

Flag a post


QR Code

Tiny Url

http://4kcan.com/s/MjUw

Related Code
ForEach Extension method for IEnumerable<T>
Invoke Extension Method
Generic Entity Framework 4.0 Base Repository
Unity Service Locator for ASP.NET MVC 3.0 Beta 1
Null Dot "Operator" Extension Method
Generic Entity Framework 4.0 Base Repository with Paging
Generic linq-to-sql repository
WCF RIA Services Unity 2.0 DomainService Factory
A Default Entity Framework 4.0 ObjectContext Factory
UnitOfWork Action filter for ASP.NET MVC and nHibernate
Make sure the web.config pages/namespace can be used together with ASP.NET MVC 3 P1 and Razor
StringFormat Extension method for HtmlHelper ASP.NET MVC
Custom C# exception class
IEnumerable<T> Exist extension method
Email validation with Regular Expression
Reflection dynamically get private fields or properties
Url Validation with Regular Expression
Extension to the HttpClient
Parsing string to enum, extension method
Method to hash passwords
Number of sealed / unsealed types in the framework

Use of Extension methods to hide "infrastructure code"

Extension methods for the ReaderWriterLockSlim class, allowing you to write more compact code, hiding necessary repetetive code.

3
839 0 1 0 0 2

For the background story of this code, check my blog.

The purpose is to demonstrate an approach of using extension methods in combination with delegates and anonymous methods to hide repetitive code structures, which allows you to remove some "noise" from the code, making it more succinct.

In short, the longer code below is a class with extension methods for the ReaderWriterLockSlim class, allowing you to write relatively compact code for executing code under different locks, while still doing it in a safe manner that will exit the locks in case of exceptions and such. Example usage of the extension methods:

private static int GetFromQueueWithExtensions()  
{  
    int result = -1;  

    _lock.RunWithUpgradeableReadLock(() =>  
    {  
        if (sharedResource.Count > 0)  
        {  
            _lock.RunWithWriteLock(() =>  
            {  
                result = sharedResource.Dequeue();  
            });  
        }  
    });  

    return result;  
}

And the full class with extension methods follows below. OK, perhaps a bit on the long side but hey, it's documented :)

public static class ReaderWriterLockSlimExtensions
{
    /// <summary>
    /// Runs the given action under a read lock
    /// </summary>
    /// <param name="readerWriterLock">The <see cref="ReaderWriterLock"/> to use for locking.</param>
    /// <param name="action">The <see cref="Action"/> to peform</param>
    /// <param name="millisecondsTimeout">The timeout in milliseconds.</param>
    /// <remarks>If <paramref name="millisecondsTimeout"/> is -1, the method will wait infinitely for acquiring the lock.</remarks>
    public static void RunWithReadLock(this ReaderWriterLockSlim readerWriterLock, Action action, int millisecondsTimeout)
    {
        if (readerWriterLock.TryEnterReadLock(millisecondsTimeout))
        {
            try
            {
                action();
            }
            finally
            {
                readerWriterLock.ExitReadLock();
            }
        }
    }

    /// <summary>
    /// Runs the given code under a read lock.
    /// </summary>
    /// <param name="readerWriterLock">The <see cref="ReaderWriterLock"/> to use for locking.</param>
    /// <param name="action">The <see cref="Action"/> to peform</param>
    public static void RunWithReadLock(this ReaderWriterLockSlim readerWriterLock, Action action)
    {
        RunWithReadLock(readerWriterLock, action, -1);
    }


    /// <summary>
    /// Runs the given code under an upgradeable read lock.
    /// </summary>
    /// <param name="readerWriterLock">The <see cref="ReaderWriterLock"/> to use for locking.</param>
    /// <param name="action">The <see cref="Action"/> to peform</param>
    /// <param name="millisecondsTimeout">The timeout in milliseconds.</param>
    /// <remarks>If <paramref name="millisecondsTimeout"/> is -1, the method will wait infinitely for acquiring the lock.</remarks>
    public static void RunWithUpgradeableReadLock(this ReaderWriterLockSlim readerWriterLock, Action action, int millisecondsTimeout)
    {
        if (readerWriterLock.TryEnterUpgradeableReadLock(millisecondsTimeout))
        {
            try
            {
                action();
            }
            finally
            {
                readerWriterLock.ExitUpgradeableReadLock();
            }
        }
    }

    /// <summary>
    /// Runs the given code under an upgradeable read lock.
    /// </summary>
    /// <param name="readerWriterLock">The <see cref="ReaderWriterLock"/> to use for locking.</param>
    /// <param name="action">The <see cref="Action"/> to peform</param>
    public static void RunWithUpgradeableReadLock(this ReaderWriterLockSlim readerWriterLock, Action action)
    {
        RunWithUpgradeableReadLock(readerWriterLock, action, -1);
    }


    /// <summary>
    /// Runs the given code under a write lock.
    /// </summary>
    /// <param name="readerWriterLock">The <see cref="ReaderWriterLock"/> to use for locking.</param>
    /// <param name="action">The <see cref="Action"/> to peform</param>
    /// <param name="millisecondsTimeout">The timeout in milliseconds.</param>
    /// <remarks>If <paramref name="millisecondsTimeout"/> is -1, the method will wait infinitely for acquiring the lock.</remarks>
    public static void RunWithWriteLock(this ReaderWriterLockSlim readerWriterLock, Action action, int millisecondsTimeout)
    {
        if (readerWriterLock.TryEnterWriteLock(millisecondsTimeout))
        {
            try
            {
                action();
            }
            finally
            {
                readerWriterLock.ExitWriteLock();
            }
        }
    }

    /// <summary>
    /// Runs the given code under a write lock.
    /// </summary>
    /// <param name="readerWriterLock">The <see cref="ReaderWriterLock"/> to use for locking.</param>
    /// <param name="action">The <see cref="Action"/> to peform</param>
    public static void RunWithWriteLock(this ReaderWriterLockSlim readerWriterLock, Action action)
    {
        RunWithWriteLock(readerWriterLock, action, -1);
    }

}

Share: twitter | facebook   Action: used | fork | flag

.net

Mark '.net' tag as 'like'

Mark '.net' tag as 'ignore'

c#

Mark 'c#' tag as 'like'

Mark 'c#' tag as 'ignore'

extension-method

Mark 'extension-method' tag as 'like'

Mark 'extension-method' tag as 'ignore'


 @fmork
116
September 17, 2010 12:03 AM

Fork

 Use of Extension methods to hide "infrastructure code" -  @fmork Friday 17, 2010 12:03 AM


1 Feedback

Awesome! :) -  @pontusm Friday 17, 2010 6:27 PM

You must log in before you can give any feedback


2 Discussion(s)

Newest Oldest
0

I'm a big fan of using Extension methods, can create clean code, but can make it hard to debug.

link | flag  | Reply

 @fredrikn "I'm the master"
3.11k
Friday 17, 2010 6:33 PM

0

I don't think extension methods are very hard to understand or debug. They are just like regular methods in my opinion.

However lamba expressions are something that many developers, especially beginners, have a hard time debugging since it breaks the usual linear flow of the code. In spite of that I still love them :)

link | flag  | Reply

 @pontusm
163
Friday 17, 2010 7:38 PM


You must log in before you can post a comment

Squeed
Made by: Fredrik Normén 2010