Monday, November 19, 2012

Easy way to have a class publish an event

This is an easy way to have a class fire an event. First declare the event as an Action<> in the class.

public class MyClass
{
    public event Action<int, string> MyEvent;
    public event EventHandler<bool> MyOtherEvent; 
 
    public MyClass()
    {
    }
    private void MyMethod(int i, string s, bool b)
    {
        // an exception will be thrown if you attempt to fire an event 
        // when there are no subscribers to the event, so we need to 
        // check first
        if (MyEvent != null)
            MyEvent(i,s);  // fires the event
                                                    
           MyOtherEvent?.Invoke<this, b>;   
    }
}

To consume the event, just declare a handler for it after instantiating the class.

    MyClass mc = new MyClass();
    mc.MyEvent += new Action(mc_MyEvent);
    mc.MyOtherEvent += Mc_MyOtherEvent;

   void mc_MyEvent(int i, string s)
   {

   }

   private static void Mc_MyOtherEvent(object sender, bool e)
   {
       
   }

Saturday, November 10, 2012

How to lock a resource

List myList = new List();
public static ReaderWriterLockSlim myLock = new ReaderWriterLockSlim();


public void myMethod(string Foo);
{
   myLock.EnterWriteLock(); //waits here if anything else has entered the lock
   myList.Add(Foo);
   myLock.ExitWriteLock();
}

public void myOtherMethod(string Bar);
{
   //Because this call doesn't use the lock, 
   //it ignores the lock and still can write to the list
   myList.Add(Bar);

   //this call would 'play nice' with other calls using the lock
   //once you use a lock on something, you should probably always
   //use a lock on that thing
   myLock.EnterWriteLock(); //waits here until the lock in myMethod is exited
   myList.Add(Bar);  
   myLock.ExitWriteLock();
}

Best way to start a parameterized thread


//use this if you do not need a handle for the thread 
//(i.e. fire and forget)
public void Foo(string myString, int myInt)
{
   new Thread(() => Do_Foo(myString, myInt)).Start();      
}

//use this if you need a handle for the thread

public Thread Foo(string myString, int myInt)
{
   Thread t = new Thread(() => Do_Foo(myString, myInt));      
   t.Start();
   return t;
}


private void Do_Foo(string myString, int myInt)
{
   ...
   The stuff you want done
   ...
}