Since the beginning of computer programming one of the problem that always baffled software developers was how to make sure that their code would run properly once threading has been introduce to the application. I’ve been experimenting with PostSharp for a couple of weeks and I thought that perhaps I can use it to discover multi threading issues in my code. But first - Can you spot the problem with the following class:public class UniqueIdFactory {
private int counter = 0; public int GetNext() {
var result = counter++; return result;
}
}Calling GetNext at the same time there is a chance that both thread would receive the same result. Fixing this issue is simple – just add Lock around counter++ or better yet use the Interlocked class. Obviously this is a simple easy to understand and debug example – in a real world project you just can’t go around adding lock to every place you happen change a variable’s value. What I came up with is a simple attribute that checks that a specific method or methods are not running on multiple threads at the same time.Read more: Helper Code
private int counter = 0; public int GetNext() {
var result = counter++; return result;
}
}Calling GetNext at the same time there is a chance that both thread would receive the same result. Fixing this issue is simple – just add Lock around counter++ or better yet use the Interlocked class. Obviously this is a simple easy to understand and debug example – in a real world project you just can’t go around adding lock to every place you happen change a variable’s value. What I came up with is a simple attribute that checks that a specific method or methods are not running on multiple threads at the same time.Read more: Helper Code
0 comments:
Post a Comment