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:
public static class Lock
{
public static 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);
}
}
return default(T);
}
public static void 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:
return Lock.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.