C # A way to compile time to ensure that methods are only called in a user interface thread, and others only in a background (non-ui) thread

Now I am doing:

Util.AssertBackgroundThread ();

or

Util.AssertUIThread ();

at the beginning of the methods. This is not so bad, but runtime error checking. The reason we use static languages ​​such as C # is to move most of the error checking to the shoulders of the compiler.

Now I don’t think it’s easy at all, but if I restrict myself to just starting threads (or using ThreadPool.QueueUserWorkItem) from my own utility methods, then it seems to me that if I tag these methods, he should be able to do a static analysis to make sure that methods intended only to be run in the user interface thread really only execute in the user interface thread?

So, two questions here.

  • Am I right that this can be checked at compile time?
  • Is there any practical way to do this in Visual Studio 2008 (with the latest version of ReSharper installed)
+5
source share
2 answers

I always liked the template:

public void GuiMethod(object param)
{
   if(this.InvokeRequired)
   {
      this.Invoke(delgateToGuiMethod, params,...)
   }
   else
   {
      //perform gui thread method
   }
}

, , gui, gui .

+5

, , , - #if DEBUG , .

.

public static void AssertUIThread()
{
#if DEBUG
   //the code goes here 
#endif
}

, , , JIT .

, , .

Edit:

, , , , FxCop post- . ... API , FxCop, . , . , , - two, . ; - , .

2:

! . , , , , . , . ( .., ), , , .

. , , , , , , . , , , , , . , ; , , , .

, . , , , - .

, . , , .

+2

All Articles