Wednesday, May 11, 2011

Generic with Lamda Expression

public void Each(IEnumerable items, Action action)
{
foreach (var item in items)
{
action(item);
}
}

public void Main()
{
List myList = new List();
myList.Add(1);
myList.Add(3);

Each(myList, i => textBox1.AppendText(i.ToString()+ "\r\n") );

new List(myList).ForEach(i => textBox1.AppendText(i.ToString() + "\r\n"));

}

Timeout Function for C#.Net

public static T Limex(Func F, int Timeout, out bool Completed)
{
var iar = F.BeginInvoke(null, new object());
if (iar.AsyncWaitHandle.WaitOne(Timeout))
{
Completed = true;
return F.EndInvoke(iar);
}
Completed = false;
return default(T);
}

// Overloaded method, for cases when we don't
// need to know if the method was terminated
public static T Limex(Func F, int Timeout)
{
bool Completed;
return Limex(F, Timeout, out Completed);
}

private string Wait()
{
Thread.Sleep(11000);
return "Paresh";
}

private bool Wait(string name)
{
return false;
}

public void Main()
{
bool Completed = false;
string str = Limex(() => Wait() , 10000, out Completed);
Completed = false;
bool b = Limex(() => Wait("paresh"), 10000, out Completed);
}