开发者

Automatically verify some threading restrictions? (C#)

Our codebase has a lot of threading restrictions encoded in comments - such as:

  • This class is thread-safe (all public methods may be safely accessed from any thread)
  • Must hold a lock on "xyz" to access/invoke any public members
  • Must only be accessed from thread "xyz" (usually but not always referring to the GUI thread)
  • This lock must be taken after lock "xyz" if both are required

The first three can be seen on both classes and individual members.

I've searched for any solutions that could at least partially verify that these constraints are satisfied. I realise that there are major limitations on the extent to which this can be done automatically, but even a little help from a tool would really help. I couldn't find any though.

Can you suggest a tool to do something along these lines? Perhaps an FxCop ruleset that works 开发者_如何学编程by encoding the above restrictions as attributes?


I am not aware of any thread-safety specific attributes, simply because it is generally too complex. And "testing" threaded code (with addition of extra Debug.Assert etc) is a common cause of heisenbugs. You could look at "CHESS"? It isn't a silver bullet, but it may be helpful.


Not sure how you'd do this at compile time, but maybe PostSharp could be used to define the constraints, rather than putting them in comments (eg. your constraints could be specified as attributes on the methods or class).


You might try to implement some FxCop custom rules (triggered using an appropriate attribute). This might help you verify some simple state (like, this class is thread safe because it contains no mutable state).

Other validation is likely to be more difficult (e.g. can FxCop validate that when field "X" is set it is always done so when we are holding a given lock) - maybe. If this is important, I would suggest to look at the FxCop SDK and see just how difficult such a test would be.

I have found that implementing custom FxCop rules is very useful, especially when we control the structure of the classes that we are testing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜