Detecting that a method is called without a lock - c#

Is there any way to detect that a certain method in my code is called without using any lock in any of the methods below in the call stack?
The goal is to debug a faulty application and find out if certain pieces of code aren't thread safe.

This seems like a decent use case for AOP (aspect oriented programming). A very basic summary of AOP is that its a method of dealing with cross cutting concerns to make code dry and modular. The idea is that if you're doing something to every method call on an object (eg. logging each call) instead of adding a log at the start and end of each method you instead you inherit the object and do that outside of the class as to not muddy its purpose.
This can be done a few ways and I'll give you an example of two. First is manually (this isn't great but can be done very easily for small casses).
Assume you have a class, Doer with two methods Do and Other. You can inherit from that and make
public class Doer
{
public virtual void Do()
{
//do stuff.
}
public virtual void Other()
{
//do stuff.
}
}
public class AspectDoer : Doer
{
public override void Do()
{
LogCall("Do");
base.Do();
}
public override void Other()
{
LogCall("Other");
base.Other();
}
private void LogCall(string method)
{
//Record call
}
}
This is great if you only care about one class but quickly becomes unfeasible if you have to do it for many classes. For those cases I'd recommend using something like the CastleProxy library. This is a library which dynamically creates a proxy to wrap any class you want. In combination with an IOC you can easily wrap every service in your application.
Here's a quick example of using CastleProxy, main points being use ProxyGenerator.GenerateProxy and pass in IInterceptors to do stuff around method calls:
[Test]
public void TestProxy()
{
var generator = new ProxyGenerator();
var proxy = generator.CreateClassProxy<Doer>(new LogInterceptor());
proxy.Do();
Assert.True(_wasCalled);
}
private static bool _wasCalled = false;
public class LogInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Log(invocation.Method.Name);
invocation.Proceed();
}
private void Log(string name)
{
_wasCalled = true;
}
}
Now, the logging portion. I'm not sure you really NEED this to be lockless, short locks might be enough but lets proceed thinking you do.
I don't know of many tools in C# that support lock free operations but the the simplest version of this I can see is using Interlocked to increment a counter of how many instances are in the method at any given time If would look something like this:
[Test]
public void TestProxy()
{
var generator = new ProxyGenerator();
var proxy = generator.CreateClassProxy<Doer>(new LogInterceptor());
proxy.Do();
Assert.AreEqual(1, _totalDoCount);
}
private static int _currentDoCount = 0;
private static int _totalDoCount = 0;
public class LogInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
if (invocation.Method.Name == "Do")
{
var result = Interlocked.Increment(ref _currentDoCount);
Interlocked.Increment(ref _totalDoCount);
if(result > 1) throw new Exception("thread safe violation");
}
invocation.Proceed();
Interlocked.Decrement(ref _currentDoCount);
}
}
Interlocked uses magical register magic to do thread safe operation (Compare-And-Swap I believe, but I don't really know). If you need more context than just "It Happened". You can use a concurrent stack or a concurrent queue which are lockless (they use interlock as well: https://msdn.microsoft.com/en-us/library/dd997305.aspx/). I would include a timestamp on these though, since I haven't used them enough to know if they promise to return elements in the order they occurred.
Like I said above, you might not NEED lock free operations but this should. I don't know if any of this is a perfect fit for you since I don't know your exact problem but it should provide you some tools to tackle this.

You could host the CLR yourself, and track the locks taken using the IHostSyncManager::CreateMonitorEvent method. You'd then need to expose your own mechanism from your host to your method called say "IsLockTaken()". You could then call that from your method in your actual code.
I think it is possible, but it would be quite a lot of work and almost certainly a complete distraction from the problem you're trying to solve, but no doubt a lot of fun!
Here's an interesting read on Deadlock detection https://blogs.msdn.microsoft.com/sqlclr/2006/07/25/deadlock-detection-in-sql-clr/

Related

Pass object into method without adding argument to method?

I have a simple interface called IEvent and it just contains this one method:
void Execute();
I have several derived classes from this interface and one of them needs access to an object that the caller of the method owns. The object is used in this fashion:
using (MyObject object = new MyObject(this.MessageService)
{
foreach (IEvent myEvent in eventList)
{
myEvent.Execute(); // <--- I need to pass object without adding argument here if possible?
}
}
I would add the object as a field in the derived class that needs access to it, but by the time I get to this part of the code, the IEvent objects are already constructed and running on a background thread. Currently, the only way I can think of is to add a setter in the IEvent interface for this object, but then I am exposing a field that most derived classes won't care about and doesn't seem like a clean solution.
I would add it as an argument to Execute(), but the problem is that the object belongs to an assembly that the assembly that contains IEvent doesn't know about (and don't want it to know about) and again 99% of the events don't care about this object anyway. Is there a better way to accomplish what I am trying to do here?
"If a class that implements IEvent does not/can not implement all the methods specified by IEvent the same way as they are declared in IEvent, that class should not implement IEvent in the first place." - Sweeper
So there's probably something wrong with your design of the whole program. I think you better revise your design a little bit and change some relationships between the classes and interfaces.
If you don't want to do that, there is another (not recommended) way to solve this problem.
Suppose your method caller is of type MethodCaller. You just change the declaration of Execute in the interface to this:
void Execute(MethodCaller obj = null);
And all the classes that implement IEvent can ignore the parameter except the class you mentioned in your question.
I'm going to piggyback on Jon Skeet's amazing knowledge of C#, .NET, CLR, IL and everything that surrounds any of those topics. You can't get to the instance of the calling object and especially the local varaible in the calling method. You can get its type, you can get the calling method through StackTrace, for example (StackTrace.GetFrames()), but none of those are going to do you any good in this situation. What you're trying to accomplish would require some heavy dive into the debugging API. As far as walking the stack, here's a quick sample I created to try see if I can figure something out for you (I made assumptions in regards to how your program is structured... obviously it's not a one to one sample):
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace SampleApp
{
class Program
{
static void Main(string[] args)
{
var eventList = new List<IEvent> { new SomeClass() };
using (MyObject obj = new MyObject(new MessageService()))
{
foreach (IEvent myEvent in eventList)
{
myEvent.Execute();
}
}
}
}
public interface IEvent
{
void Execute();
}
public class SomeClass : IEvent
{
public void Execute()
{
var stackTrace = new StackTrace();
var stackFrames = stackTrace.GetFrames();
var callingMethod = stackFrames[1].GetMethod();
var callingType = callingMethod.DeclaringType;
}
}
public class MyObject : IDisposable
{
public MessageService Service { get; }
public MyObject(MessageService service)
{
Service = service;
}
public void Dispose()
{
Service.Stop();
}
}
public class MessageService
{
public void Start() { }
public void Stop() { }
}
}
I like your question, because it presents an interesting and an unusual situation, but I'm afraid that you won't be able to accomplish your task without going outside of conventional routines that C# has in its arsenal. You may be able to pull something off with unmanaged code, but that's a different topic altogether.
However, aside from it being an interesting question... look at what you're trying to do. You have MyObject, which obviously implements IDisposable and will call Dispose() at the end of that using statement, and you're trying to grab its reference from a different assembly. I don't think this is a good idea.
I suggest revisiting your design and make use of things such as an optional parameter. May not be the "perfect" solution for your situation, as you'll pass it to every Execute in that foreach loop, but it's better than jumping through a thousand fiery hoops of debug API's.

Delegate example what's the point

Like many other posts I've found on SO, I'm trying to get my head around delegates. Hopefully this example is not classed a duplicate because I am asking a specific question about a particular example.
public delegate void HelloFunctionDelegate(string message);
public class Delegate
{
static void Main()
{
HelloFunctionDelegate del = new HelloFunctionDelegate(GoodNight); // delegate will point to the GoodNight method
del("Hello"); // invoke the delegate
}
public static void GoodMorning(string strMessage)
{
Console.WriteLine(strMessage + " and good morning!");
Console.ReadKey();
}
public static void GoodNight(string strMessage)
{
Console.WriteLine(strMessage + " and good night!");
Console.ReadKey();
}
}
So in my example I understand that my delegate is a reference to any function that matches its signature and if I pass in GoodMorning I will see:
Hello and good morning!
and if I pass in GoodNight I will see: Hello and good night!
So its kind of like going through a middle man...
I don't understand is what's the point, why wouldn't I just directly call my GoodMorning / GoodNight methods as and when I need to use them?
Maybe there are better examples for when a delegate is useful, but in this example, why don't I just bypass the middle man?
Since you are asking concretely about this example and not in general: There is no point to doing that in this particular piece of code. It teaches you the mechanics of delegates but it does not teach you the point of using them.
In short, the point is that some piece of code can take a reference to a method without knowing what method it will actually receive. It can later call that delegate at will. That enables more abstractions than otherwise possible.
Consider you have the following delegate:
public delegate void CarEvent(Car car);
And then you have an implementation like the following:
public class Car : DataRecord
{
// An event to execute when the record is deleted
public CarEvent OnDelete { get; set; }
public void Delete()
{
this.DeleteRecord(); // Deletes this record from ex. the database
if (OnDelete)
{
OnDelete(this); // Executes the event
}
}
}
By using a delegate you can subscribe different methods to the OnDelete allowing you to do different things when the record is deleted.
Ex. you can make it so when the record is deleted it's deleted from a "ListView" that holds it.
public class CarList : ListView
{
public CarList()
: base()
{
foreach (var car in CarRecords.LoadCars())
{
var listViewItem = new ListViewItem(car);
car.OnDelete = this.DeleteCarFromList;
this.Items.Add(listViewItem);
}
}
private void DeleteCarFromList(Car deletedCar)
{
this.Items.Remove(deletedCar);
}
}
Of course the above is a rough example and there is a lot more things and different kind of situations where you can use delegates and most notably if you want to use them for events you should consider implementing them using the event keyword. - https://msdn.microsoft.com/en-us/library/awbftdfh.aspx
All in all you want to use delegates when the behavior may differ depending on the overall implementation of something. Like you might want to do one thing in one situation and something else in another situation, but they should both over-all do the same thing.
If you do not need different behaviors based on implementation then there's no need to use delegates. You'd always want to call a method directly if possible.
I hope this explained it okay.

A better architecture then if(something) DoIt() else Dont()

I'm trying to create a mechanism that will allow the application to decide (in runtime) whether to execute some functionality.
"Some Functionality" can be anything, it can be c# code which is contained in several classes in several dlls, it can be UI, it can be database query execution, etc.
Most importantly, it should fit in the current existing infrastructure I have, which I cannot re-design and build from scratch.
The more I think of it, it seems like the only solution I can use would be to hold some table which will be the "functionality repository" and it will tell (by unique key) if a functionality is on / off.
Then in code, I will have to place in each spot which handles such functionality an if else statement.
E.g.
If(functionalityEnabled)?
DoFunctionality()
Else
DoTheUsusal()
Is there a better way or a better design to implement it? I would like to keep the solution as simple as possible, but on the other hand, this solution is really ugly and will eventually make my code looks like spaghetti code.
Your thoughts will be appreciated,
I'm using c# with sql server, web api for web services.
Edit:
I want to say that I appreciate the time and effort of everyone answering my question, there were some really interesting ideas that you brought up.
I eventually marked #dasblinkenlight answer since it suited by need the best, though other answers here are really good and may be useful to others.
Thank you.
If you have two classes that implement the same interface, your application can call the functionality (methods, properties) of the class without knowing exactly if it is calling the basic functionality or the alternative functionality:
IFunctionalityX {
DoIt();
}
class BasicFunctionalityX: IFunctionalityX {
public DoIt() {
// Default behaviour goes here
}
}
class PluginFunctionalityX: IFunctionalityX {
public DoIt() {
// Alternative functionality.
}
}
If PluginFunctionalityX shares parts of its implementation with BasicFunctionalityX, you may inherit it from the other, but whether you do or not doesn't really matter. As long as you use the interface, that is what counts, and you can use this method regardless of whether the classes are related or not.
In the initialization of your program, you can make the decision once and create an instance of the right class. You may store this class in some container that holds all your functionalities. FunctionalityX is a property of interface IFunctionalityX, and you can make other interfaces (and properties) for other functionalities.
if (functionalityXEnabled) {
FunctionalityContainer.FunctionalityX = new PluginFunctionality();
} else {
FunctionalityContainer.FunctionalityX = new BasicFunctionality();
}
Then, in the rest of your application, you can call your functionality through:
FunctionalityContainer.FunctionalityX.DoIt();
Instead of implementing this from scratch you may use a dependancy injection library, like Unity. This also allows you to more easily get an instance of the right functionality at the time you need it without having to create them all at the start of your program, and without writing elaborate constructor code for all fucntionalities.
You want to dispatch your code differently at runtime dependent on a configuration setting. Conditionals and polymorphism are two ways of doing so.
Conditionals
At runtime, check for values using if, switch or other lookup methods. You're already doing these.
if (configFile.cloudAccount == null) {
saveFileToDisk();
} else saveFileToCloud();
Advantages
They're conditionals, you really can't avoid having to do one at some point in any nontrivial development project
Disadvantages
Doing them at every point in your application would be painful, though. So they're best combined with other strategies to minimise their use
Polymorphism
When loading your application, read through the configuration file and construct your application's components accordingly:
interface IFileSaver { /* Used to save files in your application */ }
class DiskSaver : IFileSaver { /* The default file saving class */ }
class CloudSaver : IFileSaver { /* If they've configured a cloud account */ }
// EXAMPLE USE
int Main (...) {
// Setup your application, load a config file.
// You'll need to check the config with a conditional
// here (uh oh) but other components of your application
// will just use the IFileSaver interface
if (configFile.cloudAccount != null) {
YourApplication.FileSaver = new CloudSaver(configFile.cloudAccount);
} else {
YourApplication.FileSaver = new DiskSaver();
}
}
// Somewhere else in your application
void SaveCurrentDocument() {
// No if's needed, it was front loaded when initialising
// the application
YourApplication.FileSaver.Save();
}
Advantages
Fits in nicely with object-oriented design
All your configuration checks are front loaded. After loading in the correct classes the rest of your program will use them, oblivious to their actual implementation. Because of that, you don't need to do if checks throughout your code.
Compiler will be able to statically check type errors in your approach
Disadvantages
Only as flexible as your class's interface. Maybe you want some extra steps and checks to occur with a CloudSaver, they'd better fit into the pre-existing interface; otherwise, they won't happen.
Long story short - conditionals let you explicitly perform the checks whenever they're needed so, in principle, you get a lot of procedural flexibility. For example, maybe the SaveAs routine needs to save files slightly differently than the Save routine. However, as you've identified, this leads to long repetitive code. In those cases, structuring your code to use polymorphism might help out.
Either way, you will almost certainly need to have some amount of conditional checks wherever there is flexibility in your application.
Note: There are many other ways of achieving runtime config checks, I'm just pointing out the most common (and usually straightforward)
A once-popular quip among OO programmers has been that every conditional in the code indicate a missed opportunity to subclass. Although this rule is far from being universal, and it falls short when it comes to composition, there is a grain of truth to it, especially when you see the same condition popping up in multiple ifs across different methods of the same class.
A common way of dealing with ifs like that is using some combination of inheritance and composition, and moving the decision to a single place where your object is being created.
The inheritance way looks like this:
interface Doer {
void doSomething();
}
class BasicDoer implements Doer {
public void doSomething() {
...
}
}
class EnhancedDoer extends BasicDoer {
public void doSomething() {
base.doSomething();
...
}
}
// At construction time:
Doer doer;
if (someCondition)
doer = new BasicDoer();
else
doer = new EnhancedDoer();
The composition way looks like this:
interface Doer {
void doSomething();
}
// Create several implementations of Activity, then...
// At construction time:
List<Doer> doers = new ArrayList<>();
if (someCondition1)
doers.add(new SomeKindOfDoer());
if (someCondition2)
doers.add(new AnotherKindOfDoer());
if (someCondition3)
doers.add(new YetAnotherKindOfDoer());
Now instead of an if you do this:
for (Doer d : doers) {
d.doSomething();
}
If it's just a single condition then you have no choice but to use if else and is perfect for single conditions.
If you have more then 1 condition, you may think of using Switch statement.
As far as you are worried about your code going to look complicated with if else statement, put your code within functions,
if(condition)
{
DoThis();
}
else
{
DoSomethingElse();
}
Maybe something similar to strategy design pattern (incapsulation of behaviour) will make it more managable if functionality doesn't require lots of interaction with object data (though interaction is possible). Pros: readable extendable code, cons: lots of code.
namespace SomethingLikeStrategy
{
public interface Behaviour {
void doThis();
void changeM(ref int m);
void doThat();
}
public class BehaviourOriginal : Behaviour {
public void doThis() {
Console.WriteLine("foo");
}
public void changeM(ref int m) {
m = 20;
}
public void doThat() {
throw new Exception("not implemented");
}
}
public class BehaviourSpecial : Behaviour {
public void doThis() {
Console.WriteLine("bar");
}
public void changeM(ref int m) {
m = 10;
}
public void doThat() {
throw new Exception("not implemented");
}
}
public class MyClass {
Behaviour mBehaviour;
int mM = 0;
public MyClass() {
mBehaviour = new BehaviourOriginal();
}
public void setSpecialBehaviour(bool special) {
if (special) {
mBehaviour = new BehaviourSpecial();
} else {
mBehaviour = new BehaviourOriginal();
}
}
public void doThis() {
mBehaviour.doThis();
}
public void doThat() {
mBehaviour.doThat();
}
public void changeM() {
mBehaviour.changeM(ref mM);
}
public void printM() {
Console.WriteLine(mM);
}
}
class Program
{
public static void Main(string[] args)
{
MyClass myClass = new MyClass();
myClass.doThis();
myClass.setSpecialBehaviour(true);
myClass.doThis();
myClass.setSpecialBehaviour(false);
myClass.printM();
myClass.changeM();
myClass.printM();
myClass.setSpecialBehaviour(true);
myClass.changeM();
myClass.printM();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}

Service Locator easier to use than dependency Injection?

The application I am working on is relying on Autofac as DI container and one of the reasons that made me decide to use it, among others, was the delegate factory feature (see here)
This works fine for all cases where I need to recreate the same elements several times as is the case of some reports and related screens. Some reports (even those of the same type) are executed concurrently but they change only by their user-defined parameters so it makes sense (I think) to inject factories in order to create instances, passing the free parameters and leave the rest to the application.
The problem comes with the fact that each report is made of a variable number of sub reports (tasks) and each task implements an ITask interface. Each report may have up to 50 different tasks to use and each task encapsulates a precise business operation. One option I have is to inject delegate factories for and create them when needed.
These tasks have to be dynamically generated by factories and something like:
var myTaskA = _taskFactoryConcreteTaskA();
var myTaskB = _taskFactoryConcreteTaskB();
var myTaskC = _taskFactoryConcreteTaskC();
...
var myTaskZZ = = _taskFactoryConcreteTaskZZ();
requires a lot of manual wiring (delegates, constructor, backing fields etc) while something like
var myTaskA = _taskFactory.Create<ConcreteTaskA>();
var myTaskB = _taskFactory.Create<ConcreteTaskB>();
var myTaskC = _taskFactory.Create<ConcreteTaskC>();
...
var myTaskZZ = _taskFactory.Create<ConcreteTaskZZ>();
would be incredibly less work especially if the _taskFactory wraps the container as shown in this other post, but also it would basically mean I am using a service locator to create my tasks.
What other options do I have that may be suitable to solve this?
(NOTE: there is a good chance I am completely off track and that I have to read a lot more about DI, in which case any contribution would be even more important)
Since the factories indicated in the question don't take any arguments, using a factory smells of a Leaky Abstraction. As Nicholas Blumhardt points out in his answer, a better approach might be to simply inject each task into the consumer.
In this case, since all the tasks implement the same interface, instead of injecting up to 50 different ITask instances, you can compose them:
public class MyConsumer
{
private readonly IEnumerable<ITask> tasks;
public MyConsumer(IEnumerable<ITask> tasks)
{
this.tasks = tasks;
}
public void DoSomething()
{
foreach (var t in this.tasks)
{
// Do something with each t
}
}
}
Alternatively, you can compose the sequence of ITasks into a Composite, which is actually my preferred solution:
public CompositeTask : ITask
{
private readonly IEnumerable<ITask> tasks;
public CompositeTask(IEnumerable<ITask> tasks)
{
this.tasks = tasks;
}
// Implement ITask by iterating over this.tasks
}
This would simplify the consumer and turn the fact that there are more than one task to be performed into an implementation detail:
public class MyConsumer
{
private readonly ITask task;
public MyConsumer(ITask task)
{
this.task = task;
}
public void DoSomething()
{
// Do something with this.task
}
}
One approach worth investigating is to break the problem into'units of work' that use a set of related tasks:
public class WorkItem1 : ISomeWork
{
public WorkItem1(Task1 t1, Task2 t2...) { }
public void DoSomething() { ... }
}
Then, your use of factories would come down towards someWorkFactory().DoSomething(), possibly for a few different kinds of 'something'.
A class having a large number of dependencies, on factories or anything else, usually points to there being smaller, more focused classes waiting to be discovered to break up the work.
Hope this helps.

Need a pattern to call Verify method for every instance method pattern

I have the following code:
class Foo
{
public Foo()
{
Size = true;
}
private bool _size;
protected bool Size
{
get { _size; }
set { _size = value; }
}
}
class CrazyFoo : Foo
{
public void First()
{
if (!Size)
return;
}
public void Second()
{
if (!Size)
return;
}
public void Finished()
{
if (!Size)
return;
}
}
What is the best way to implement this sort of pattern, as it drives me nuts to type
if(!Size) return;
perhaps I can do it with attributes or AOP?
What is the best and simplest way?
Thanks
If you have the same guard statement at the beginning of too many methods, you can create a method called executeWithGuard:
private void executeWithGuard(Action method)
{
if (HeadSize) method();
}
Then you could do this:
public void ScreenFirstShot()
{
executeWithGuard(() =>
{
// code here
});
}
public void ScreenSecondShot()
{
ExecuteWithGuard(() =>
{
// code here
});
}
public void CrazyUp()
{
ExecuteWithGuard(() =>
{
// code here
});
}
There's no less code doing this... in fact, there's probably more code, but it does allow you to not have to do a find/replace if your guard condition ever changes. I'd only suggest it as a last resort, though. It's very possible that your real problem is that you're doing your validation too far down the call tree. If you can do it at a higher level, you may save yourself from all of this validation.
ALSO
Have a look at the null object patttern. This pattern can be used in some special cases to prevent or simplify state checking.
ALSO (rev 2)
It's hard to know what your intent is since the question focuses on a specific solution, but if you're executing these methods sequentially, you can look at using the strategy pattern, and putting the check in your base strategy class.
From a "pattern" standpoint, though, this doesn't seem onerous to me. It seems perfectly reasonable to me to type:
if(!Size)
return;
You're explicitly handling the cases you want. In your case, this check is pretty specific to what you are working with, from what I can tell (from your original + edits). I'd personally choose a more obvious name, since it does seem a little strange (even in your original), and not completely obvious what's happening.
Even with AOP, you'd be adding some other information here on each method, to make sure your aspect was handled.
Maybe just use one method and an Enum with the values First, Second, Finished etc.? It's hard to tell because, apart from that one check, you don't say what is common. AOP could be a solution, but maybe not, since aspects are usually more general in their conceptional nature.
BTW, maybe choose a different naming for your samples in the future, this may offend some people. (Edited to match new naming)

Categories