I have a class with quite a lot of public functions. I want to prevent the situation that any of the function is executed when another function is already running. So I included a semaphore in every function like this:
public bool FunctionX(int a)
{
if (semaphore.Wait(0))
{
try
{
return DoSomething(a);
}
finally
{
semaphore.Release();
}
}
else
return false;
}
This works, but is there a more elegant way, where I do not have to write this wrapping semaphore stuff each time? I am thinking about something of the form
public bool FunctionX(int a)
{
WrapSemaphoreAround(DoSomething(a))
}
Note that the signature of every function is different, not necessarily bool as return value and int as parameter, so it also has to work with
public string FunctionY(byte a, bool b)
{
WrapSemaphoreAround(DoAnotherThing(a, b))
}
Is this even possible in C#?