Best way to implement RAII idiom in c# - c#

I have a class which manipulates a resource which is shared by multiple threads. The threads pass around control of a mutex in order to manage access to the resource. I would like to manage control of the mutex using the RAII idiom via a disposable object.
There is an additional caveat. When the class begins an operation to manipulate the resource, it is possible that the operation is no longer necessary, or may no longer be performed. This is the result of user action which occurs after the operation has been scheduled to be carried out -- no way around it unfortunately. There are many different operations which might possibly be carried out, and all of them must acquire the mutex in this way. I'm imagining it will look something like this, for example:
public void DoAnOperation()
{
using(RAIIMutex raii = new RAIIMutex(TheMutex))
{
if(ShouldContinueOperation())
{
// Do operation-specific stuff
}
}
}
However, because I'm lazy, I'd like to not have to repeat that if(ShouldContinueOperation()) statement for each operation's function. Is there a way to do this while keeping the // Do operation-specific stuff in the body of the using statement? That seems like the most readable way to write it. For example, I don't want something like this (I'd prefer repeating the if statement if something like this is the only alternative):
public void DoAnOperation()
{
var blaarm = new ObjectThatDoesStuffWithRAIIMutex(TheMutex, ActuallyDoAnOperation);
blaarm.DoAnOperationWithTheMutex();
}
private void ActuallyDoAnOperation()
{
// Do operation-specific stuff
}

It is not entirely clear what ShouldContinueOperation depends on, but assuming that it can be a static function (based on the example code provided in the question), you might like something along the lines of:
public static void TryOperation(Mutex mutex, Action action)
{
using (RAIIMutex raii = new RAIIMutex(mutex))
{
if (ShouldContinueOperation())
action();
}
}
Which you can then use like:
RAIIMutex.TryOperation(TheMutex, () =>
{
// Do operation-specific stuff
});
This combines the using and the ShouldContinueOperation check in one line for the caller. I'm not quite sure about the readability of the lambda syntax used, but that's a matter of personal preference.

Related

How can i make and call a method without any paramaters?

I want to simply call my method like this:
collect.clear;
instead of,
collect.clear();
in other words, I want to make this method
class collect
{
public List<string> list = new List<string>();
public void Clear()
{
list.clear();
}
}
to be called like so
static void Main(string[] args)
{
collect.clear;
}
is this possible or not at all.
I want to simply call my method like this: collect.clear; instead of, collect.clear();
Well, frankly: you don't get to decide what the language syntax is, and in C#, the syntax for invoking a method is: collect.clear();.
Basically, you can't do what you want. You could make it a property, but then you'd need to discard the result (so it can choose between get and set), i.e. with a property get called clear, _ = collect.clear; - frankly I think that's a step back from the (). It is also a terrible idea from the basis of unexpected side-effects; most UI elements (including the debugger) and libraries (serializers, etc) think that they can freely evaluate property gets, so it would be very unexpected it reviewing a property had the side effect of clearing the data! Basically, don't do that.
So; embrace the (). They express the intent here, for your benefit, the benefit of people reviewing/maintaining it, and for the benefit of the compiler.

Returning From Within a Callee

I have a client/server architecture rolled into the same executable project. It also supports user-code access via script. As such, in my code there are a lot of checks on critical methods to ensure the context in which they are being called is correct. For example, I have a whole lot of the following:
public void Spawn(Actor2D actor)
{
if (!Game.Instance.SERVER)
{
Util.Log(LogManager.LogLevel.Error, "Spawning of actors is only allowed on the server.");
return;
}
//Do stuff.
}
I would like to cut down on this duplication of code. Does there exist something in C# what would give me the functionality to do something like:
public void Spawn(Actor2D actor)
{
AssertServer("Spawning of actors is only allowed on the server.");
//Do stuff.
}
Even a generic message like "[MethodNameOfPreviousCallOnStack] can only be called on the server." would be acceptable. But it would have to also return from the caller as well (in this case Spawn()), as to function like an abort. Similar to an assert, but instead of generating an exception just returns. Thanks!
You should consider going up another level of abstraction and add metadata to the method to describe these constraints:
[ServerOnly]
public void Spawn(...)
{
...
}
Then use a AOP library like Dynamic Proxy to intercept calls to the method. If the method has the [ServerOnly] attribute, then you can check the context you are running in then return out if it is incorrect.
This approach will get you pretty close:
public void RunOnServerOnly(Action execFunc, string errorMessage)
{
if (!Game.Instance.SERVER)
{
Util.Log(LogManager.LogLevel.Error, errorMessage);
}
else
{
execFunc();
}
}
Then you call it:
RunOnServerOnly(() => Spawn(newActor), "Spawning of actors is only allowed on the server.");
Explanation:
To get rid of the duplicated code, you have one function that performs the check and logging. You give it an action (generic delegate) to perform if the check passes. It runs the if statement, logs if it isn't on a server, and otherwise just runs the function.
I would tend to agree that exceptions are probably the better route to go, but the above meets your requirements.
If possible add a ServerContext object that describes the current server instance to the method argument list.
public void Spawn(ServerContext context, Actor2D actor)
{
// do stuff
}
This makes it difficult for the caller to execute this method without a valid context. In that way you are enforcing the rule at compile time.

Avoiding repeatedly allocating an Action object without a variable / member

Often I need to minimise object allocations within code that runs very frequently.
Of course I can use normal techniques like object pooling, but sometimes I just want something that's contained locally.
To try and achieve this, I came up with the below:
public static class Reusable<T> where T : new()
{
private static T _Internal;
private static Action<T> _ResetAction;
static Reusable()
{
_Internal = Activator.CreateInstance<T>();
}
public static void SetResetAction(Action<T> resetAction)
{
_ResetAction = resetAction;
}
public static T Get()
{
#if DEBUG
if (_ResetAction == null)
{
throw new InvalidOperationException("You must set the reset action first");
}
#endif
_ResetAction(_Internal);
return _Internal;
}
}
Currently, the usage would be:
// In initialisation function somewhere
Reuseable<List<int>>.SetResetAction((l) => l.Clear());
....
// In loop
var list = Reuseable<List<int>>.Get();
// Do stuff with list
What I'd like to improve, is the fact that the whole thing is not contained in one place (the .SetResetAction is separate to where it's actually used).
I'd like to get the code to something like below:
// In loop
var list = Reuseable<List<int>>.Get((l) => l.Clear());
// Do stuff with list
The problem with this is that i get an object allocation (it creates an Action<T>) every loop.
Is it possible to get the usage I'm after without any object allocations?
Obviously I could create a ReuseableList<T> which would have a built-in Action but I want to allow for other cases where the action could vary.
Are you sure that creates a new Action<T> on each iteration? I suspect it actually doesn't, given that it doesn't capture any variables. I suspect if you look at the IL generated by the C# compiler, it will cache the delegate.
Of course, that's implementation-specific...
EDIT: (I was just leaving before I had time to write any more...)
As Eric points out in the comment, it's not a great idea to rely on this. It's not guaranteed, and it's easy to accidentally break it even when you don't change compiler.
Even the design of this looks worrying (thread safety?) but if you must do it, I'd probably turn it from a static class into a "normal" class which takes the reset method (and possibly the instance) in a constructor. That's a more flexible, readable and testable approach IMO.

Help naming a class that has a single public method called Execute()

I have designed the following class that should work kind of like a method (usually the user will just run Execute()):
public abstract class ??? {
protected bool hasFailed = false;
protected bool hasRun = false;
public bool HasFailed { get { return hasFailed; } }
public bool HasRun { get { return hasRun; } }
private void Restart() {
hasFailed = false;
hasRun = false;
}
public bool Execute() {
ExecuteImplementation();
bool returnValue = hasFailed;
Restart();
return returnValue;
}
protected abstract void ExecuteImplementation();
}
My question is: how should I name this class? Runnable? Method(sounds awkward)?
Naming a class is all about a good design. You have to know which use cases this class will be part of, which responsibility it will take and what collaborations will this class take part in. Naming class without context can only do harm. Naming class after a pattern just because the pattern uses similar names is even worse, because it might confuse any reader who knows something about patterns, whcih is exactly opposite of what patterns try to achieve - name common decisions/solutions/designs/etc... Your class can be Runnable, Executable, Method, Procedure, Job, Worker, RestartableExecutor, Command, Block, Closure, Functor and virtually pretty much anything without further information.
Possibilities:
action
command
worker
method
I like action, personally.
I guess a good question to ask yourself would be what you are executing. Then you might get an idea of what to name it.
For example, if you are executing a file and folder scan, you could name the class FileAndFolderScan.
FileAndFolderScan.Execute();
It sure looks like a Task to me.
Usually the Command pattern uses classes with an Execute() method. Is that more or less what you're trying to accomplish? I guess it's close enough for me; I would call it a Command or Worker or something similar.
Do you know about BackgroundWorker?
The .NET Framework already has a class that does this (several, actually). They're called delegates.
If it's really doing a lot more than just executing a method - performing error handling or that sort of thing - then name it for what it actually does, not how it's implemented.
If you absolutely have to implement a totally generic and abstract class that does nothing but encapsulate an arbitrary method and some sort of success/failure status (why?), then... task, worker, command, instruction, request, activity, etc... pick any of the above, they all mean pretty much the same thing in this context.
At my work we were stuck on .NET 2.0 for a while (pre-Action and Func delegates) and I had been using a bunch of overloaded generic delegates with the same signatures called Runner and Returner. Seems to me you could go with Runner and have a pretty clear self-describing class.
Alternately, why not just go with something like Executable or Executor?
Task
Client code should look good with this.
//create instance of Task implementation
Task myTask = TaskFactory.CreateTask();
//Execute the task
myTask.Execute()
You could call it an Executioner. :)
Quick Answer:
You already have several suggestions like "Task", "Process", "Job", even "Command".
Complementary comments:
Any object has a life cycle, a "start" operation, usually the constructor, a "finish" operation, usually a "Dispose" or destructor, and unleast a single main operation like your "Execute()", but there can be more.
In you code, the constructor or destructor are internally managed by your compiler, but sometimes do some other stuff like open and closing files.
You may want to learn more about the Command Design pattern, as mention by previous answers, it seems to fit your case.

Useful mini patterns (not design patterns)

My most used mini pattern is:
VideoLookup = new ArrayList { new ArrayList { buttonVideo1, "Video01.flv" },
new ArrayList { buttonVideo2, "Video02.flv" },
new ArrayList { buttonVideo3, "Video03.flv" },
new ArrayList { buttonVideo4, "Video04.flv" },
new ArrayList { buttonVideo4, "Video04.flv" }
};
This means that rather than a switch statement with a case for each button I can instead just compare the button that was clicked with each item in the ArrayList. Then when I've found a match I launch the correct file (although the action that's the 2nd part the "lookup" could be a delegate or anything else).
The main benefit is that I don't have the problem of remembering to add all the correct code for each switch statement case, I just add a new item to the lookup ArrayList.
(Yes I know using an ArrayList isn't the best way to go, but it's old code. And I know that looping through an array each time isn't as efficient as using a switch statement, but this code isn't in a tight loop)
Does anyone else have any mini-patterns they use that save time/effort or make code more readable? They don't have to just be GUI related.
Update: Don't copy this code, I knew it was bad, but I didn't realise how bad. Use something like this instead.
Hashtable PlayerLookup = new Hashtable();
PlayerLookup.Add(buttonVideo1, "Video01.flv");
PlayerLookup.Add(buttonVideo2, "Video02.flv");
PlayerLookup.Add(buttonVideo3, "Video03.flv");
PlayerLookup.Add(buttonVideo4, "Video04.flv");
string fileName = PlayerLookup[currentButton].ToString();
please please please omg use this version.
VideoLookup = new Dictionary<Button, string> {
{ buttonVideo1, "Video01.flv" },
{ buttonVideo2, "Video02.flv" },
{ buttonVideo3, "Video03.flv" },
{ buttonVideo4, "Video04.flv" },
{ buttonVideo4, "Video04.flv" }
};
You could just create a struct or object that has a button reference and a string representing the file name and then a List of these things. Or, you could just use a Dictionary and make it even easier on yourself. Lots of ways to improve. :)
On the subject of switches, I write this kind of thing a lot:
public Object createSomething(String param)
{
return s == null ? new NullObject() :
s.equals("foo") ? new Foo() :
s.equals("bar") ? new Bar() :
s.equals("baz") || s.equals("car") ? new BazCar() :
new Object();
}
I think it looks more readable compared to regular switch statements and has the ability to have more complex comparisons. Yeah, it'll be slower because you need to compare each condition but 99% of the time that doesn't matter.
In Java, I sometimes find that private inner classes which implement a public interface can be very helpful for objects composed of tightly-coupled elements. I've seen this mini-pattern (idiom) discussed in the context of creating UIs with Allen Holub's Visual Proxy architecture, but not much beyond that. As far as I know it doesn't have a name.
For example, let's say you have a Collection interface that can provide an Iterator:
public interface Collection
{
...
public Iterator iterate();
}
public interface Iterator
{
public boolean hasNext();
public Object next();
}
If you have a Stack that implements Collection, then you could implement its Iterator as a private inner class:
public class Stack implements Collection
{
...
public Iterator iterate()
{
return new IteratorImpl();
}
private class IteratorImpl implements Iterator
{
public boolean hasNext() { ... }
public Object next() { ... }
}
}
Stack.IteratorImpl has complete access to all of Stack's private methods and fields. At the same time, Stack.IteratorImpl is invisible to all except Stack.
A Stack and its Iterator will tend to be tightly coupled. Worst case, implementing Stack's Iterator as a public class might force you to break Stack's encapsulation. The private inner class lets you avoid this. Either way, you avoid polluting the class hierarchy with something that's really an implementation detail.
In my last job I wrote a C# version of the Enforcements concept introduced in C++ by Andrei Alexandrescu and Petru Marginean (original article here).
This is really cool because it lets you interweave error handling or condition checking in with normal code without breaking the flow - e.g.:
string text = Enforce.NotNull( myObj.SomeMethodThatGetsAString(), "method returned NULL" );
This would check if the first argument is null, throw an EnforcementException with the second argument as the message if it is, or return the first argument otherwise. There are overloads that take string formatting params too, as well as overloads that let you specify a different exception type.
You could argue that this sort of thing is less relevant in C# because the runtime checking is better and already quite informative - but this idiom lets you check closer to the source and provide more information, while remaining expressive.
I use the same system for Pre and Post condition checking.
I might write an Open Source version and link it from here.
for when I'm churning out code fast (deadlines! deadlines! why am I on stackoverflow.com? deadlines!), I wind up with this kind code:
Button1.Click += (o,e) => { DoSomething(foo); };
Will this cause me memory leaks at some point? I'm not sure! This probably deserves a question. Ack! Deadlines!
For Windows forms I'll often use the Tag field to put a psuedo-command string so that I can have a single event handler for a shared set of buttons. This works especially well for buttons that do pretty much the same thing but are parameterized.
In your first example, I would set the Tag for the buttons equal to the name of the video file -- no lookup required.
For applications that have some form of text-based command processor for dispatching actions, the Tag is a string that is just fed into the command processor. Works nice.
(BTW: I've seen the term "idiom" used for mini-patterns...)
A new idiom that I'm beginning to see in C# is the use of closure parameters that encapsulate some configuration or setup that the method will need to function. This way, you can control the relative order that code must run from within your method.
This is called a nested closure by Martin Fowler: http://www.martinfowler.com/dslwip/NestedClosure.html
Perhaps there's already a better way of doing this (vbEx2005/.Net2.0), but I've found it useful to have a class of generic delegate-creators which accept a method that takes some parameters, along with the values of either all, or all but one, of those parameters, and yields a delegate which, when invoked, will call the specified function with the indicated parameters. Unlike ParamArray-based things like ParameterizedThreadStart, everything is type-safe.
For example, if I say:
Sub Foo(param1 As Integer, param2 As String)
...
End Sub
...
Dim theAct as Action(of Integer) = _
ActionOf(of Integer).NewInv(AddressOf Foo,"Hello there")
theAct(5)
...
the result will be to call Foo(5, "Hello there") on object where Foo was declared. Unfortunately, I end up having to have separate generic classes and methods for every different number of parameters I want to support, but it's nicer to have all the cut-and-paste in one file than to have extra code scattered about everywhere to create the appropriate delegates.

Categories

Resources