I'm a C# developer having worked with .Net since it was in beta. Before that I mainly worked in C and C++. I have been developing commercial software for more than 20 years. I also mess around with microprocessors, but that's just for fun. I live near Cambridge, England and work from home in my 'silicon shed'.

Blogroll

I'm working on a lot of multithreaded code at the moment. In the past I have made use of the lock keyword in C#, but I'm not doing that anymore because it is much better to have a timeout. However, I don't like having lots of sections like this in my code:

if (System.Threading.Monitor.TryEnter(objLock, TIMEOUT))

{

try

{

// do stuff here...

}

finally

{

System.Threading.Monitor.Exit(objLock);

}

}

...which is the equivalent of using the lock statement, but with a timeout specified. Still, what I'd like to see in my code is something like this:

lock (objLock,TIMEOUT)

{

// do stuff here...

}

Which would be more pretty. And since I like pretty code, I decided to see how close I could get to that. This is my current solution:

publicstaticclassLock

{

publicstatic T Try<T>(object objLock, int timeout, Func<T> f)

{

if (System.Threading.Monitor.TryEnter(objLock, timeout))

{

try

{

return f.Invoke();

}

finally

{

System.Threading.Monitor.Exit(objLock);

}

}

returndefault(T);

}

publicstaticvoid Try(object objLock, int timeout, Action f)

{

if (System.Threading.Monitor.TryEnter(objLock, timeout))

{

try

{

f.Invoke();

}

finally

{

System.Threading.Monitor.Exit(objLock);

}

}

}

}

So far, that is as close as I can get, it means that I can do two things:

Lock.Try(objLock, TIMEOUT, delegate

{

// stuff here...

});

or, if I need to return a value, then this:

returnLock.Try<int>(objLock,TIMEOUT,delegate

{

// stuff here...

return 0;

});

Because the second example uses generics, then I can return anything I like by specifying the type inside the angled brackets. Now I feel that my code is a lot more prettier which is a nice way to finish off on a Friday.