February 21, 2013

De Morgan's Theorem

Wikipedia has more info on this
I am always forgetting this rule:
NOT (P AND Q) = (NOT P)  OR (NOT Q) 
or in more generealised form:
NOT (P  OR Q  OR R  OR ...) = (NOT P) AND (NOT Q) AND (NOT R) AND ...
NOT (P AND Q AND R AND ...) = (NOT P)  OR (NOT Q)  OR (NOT R)  OR ...
In C#
!(P || Q) = (!P) && (!Q)
!(P && Q) = (!P) OR (!Q) 
Can be useful sometimes to improve code readability but do not use it for optimisation (let the compiler do that)

February 4, 2013

A Generic ThreadPool.QueueUserWorkItem

Found the idea here
A generic version of the "ThreadPool.QueueUserWorkItem" method. I believe that this really belongs in the .NET framework
// Generic QueueUserWorkItem implementation, the thread routine signature
public delegate void ThreadRoutine<T>(T state);

/// <summary>
/// Extensions to the ThreadPool class
/// </summary>
public static class ThreadPoolExtender
  /// <summary>
  /// Queue specified thread routine/work item for processing 
  /// on a thread pool thread.
  /// </summary>
  /// <typeparam name="T">Thread routine parameter type.</typeparam>
  /// <param name="state">object containing state for the thread 
  /// routine.</param>
  /// <param name="threadRoutine">Thread routine/work item to queue 
  /// that shall be executed on a thread pool thread</param>
  /// <returns>indicates success.</returns>
  public static bool QueueUserWorkItem<T>(T state, ThreadRoutine<T> threadRoutine)
    return ThreadPool.QueueUserWorkItem(s => threadRoutine((T)s), state);
Sample usage with an an anonymous object
res = ThreadPoolExtender.QueueUserWorkItem(
    // Anonymous type, saves defining a class type just for this call
    new { onFinishedDelegate = onFinished, Folderpath = folderPath },
    (input) => // input matches the anonymous object defined in the line above
    {   // Start worker thread work
        bool outcome = this.DoSomething(input.Folderpath);
        // In this example we callback on a delegate to indicate that 
        // the thread work is complete
    }); // End worker thread work