C # Coding specification 4

Source: Internet
Author: User
Framework-Specific Guidelines

Multithreading
  1. Use synchronization domains.
    Avoid manual synchronization, because that often leads to deadlocks and race
    Conditions.

  2. Never call outside your synchronization domain.

  3. Manage asynchronous call completion on a callback method. Do
    Not wait, poll, or block for completion.

  4. Always name your threads:

    Thread currentThread = Thread.CurrentThread;
    string threadName = "Main UI Thread";
    currentThread.Name = threadName;

    The name is traced in the debugger Threads window, making debug
    Sessions more productive.

  5. Do not callSuspend ()OrResume ()On
    Thread.

  6. Do not callThread. Sleep (), Memory T in the following
    Conditions:

    1. Thread. Sleep (0)Is an acceptable optimization
      Technique to force a context switch.

    2. Thread. Sleep ()Is acceptable in testing or simulation
      Code.

  7. Do not callTHRead. SpinWait ().

  8. Do not callThread. Abort ()To terminate threads. Use
    A synchronization object instead to signal the thread to terminate.

  9. Avoid explicitly setting the thread priority to control
    Execution. You can set the thread priority based on task semantics (such
    ThreadPriority. BelowNormalFor a screensaver ).

  10. Do not read the value ofThreadStateProperty. Use
    Thread. IsAlive ()To determine whether the thread is dead or
    Alive.

  11. Do not rely on setting the thread type to background thread
    Application shutdown. Use a watchdog or other monitoring entity
    Deterministically kill threads.

  12. Do not use the thread local storage unless thread affinity is
    Guaranteed.

  13. Do not callThread. MemoryBarrier ().

  14. Never callThread. Join ()Without checking that you
    Are not joining your own thread:

    void WaitForThreadToDie(Thread thread)
    {
    Debug.Assert(Thread.CurrentThread.ManagedThreadId != thread.ManagedThreadId);
    thread.Join( );
    }

  15. Always useLock ()Statement rather than explicit
    MonitorManipulation.

  16. Always encapsulateLock ()Statement inside
    Object it protects:

    public class MyClass
    {
    public void DoSomething( )
    {
    lock(this)
    {...}
    }
    }

  17. You can use synchronized methods instead of writing
    Lock ()Statement yourself.

  18. Avoid fragmented locking.

  19. Avoid usingMonitorTo wait or pulse objects. Use
    Manual or auto-reset events instead.

  20. Do not use volatile variables. Lock your object or fields
    Instead to guarantee deterministic and thread-safe access. Do not use
    THRead. VolatileRead (),Thread. VolatileWrite (), Or
    VolatileModifier.

  21. Avoid increasing the maximum number of threads in the thread
    Pool.

  22. Never StackLock ()Statements, because that does not
    Provide atomic locking:

    MyClass obj1 = new MyClass( );
    MyClass obj2 = new MyClass( );
    MyClass obj3 = new MyClass( );

    //Do not stack lock statements
    lock(obj1)
    lock(obj2)
    lock(obj3)
    {
    obj1.DoSomething( );
    obj2.DoSomething( );
    obj3.DoSomething( );
    }

    UseWaitHandle. WaitAll ()
    Instead.

Serialization
  1. Prefer the binary formatter.

  2. Mark serialization event-handling methods as private.

  3. Use the genericIGenericFormatterInterface.

  4. Always Mark non-Sealed Classes as serializable.

  5. When implementingIDeserializationCallbackOn
    Non-sealed class, make sure to do so in a way that allows subclasses to call
    Base class implementationOnDeserialization ().

  6. Always Mark unserializable member variables
    Non-serializable.

  7. Always Mark delegates on a serialized class as non-serializable
    Fields:

    [Serializable]
    public class MyClass
    {
    [field:NonSerialized]
    public event EventHandler MyEvent;
    }

Remoting
  1. Prefer administrative configuration to programmatic
    Configuration.

  2. Always implementIDisposableOn single-call
    Objects.

  3. Always prefer a TCP channel and a binary format when using
    Remoting, unless
    Firewall is present.

  4. Always provideNullLease for a singleton
    Object:

    public class MySingleton : MarshalByRefObject
    {
    public override object InitializeLifetimeService( )
    {
    return null;
    }
    }

  5. Always provide a pointer sor for a client-activated object.
    Using sor shoshould return the initial lease time.

  6. Always unregister the operating sor on client application
    Shutdown.

  7. Always put remote objects in class libraries.

  8. Avoid using soapsuds.exe.

  9. Avoid hosting in IIS.

  10. Avoid using uni-directional channels.

  11. Always load a remoting configuration file inMain (),
    Even if the file is empty and the application does not use remoting:

    static void Main( )
    {
    RemotingConfigurationEx.Configure( );
    /* Rest of Main( ) */
    }

  12. Avoid usingActivator. GetObject ()And
    Activator. CreateInstance ()For remote object activation. Use
    NewInstead.

  13. Always register port 0 on the client side, to allow
    Callbacks.

  14. Always elevate type filtering to full on both client and host,
    To allow callbacks.

Security

  1. Always demand your own strong name on assemblies and components
    That are private to the application, but are public (so that only you can use
    Them ):

    public class PublicKeys
    {
    public const string MyCompany = "1234567894800000940000000602000000240000"+
    "52534131000400000100010007D1FA57C4AED9F0"+
    "A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C83"+
    "4C99921EB23BE79AD9D5DCC1DD9AD23613210290"+
    "0B723CF980957FC4E177108FC607774F29E8320E"+
    "92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99"+
    "285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF"+
    "0FC4963D261C8A12436518206DC093344D5AD293";
    }

    [StrongNameIdentityPermission(SecurityAction.LinkDemand,
    PublicKey = PublicKeys.MyCompany)]
    public class MyClass
    {...}

  2. Apply encryption and security protection on Application
    Configuration files.

  3. When importing an InterOP method, assert unmanaged code
    Permission and demand appropriate permission instead:

    [DllImport("user32",EntryPoint="MessageBoxA")]
    private static extern int Show(IntPtr handle,string text,string caption,
    int msgType);
    [SecurityPermission(SecurityAction.Assert,UnmanagedCode = true)]
    [UIPermission(SecurityAction.Demand,
    Window = UIPermissionWindow.SafeTopLevelWindows)]
    public static void Show(string text,string caption)
    {
    Show(IntPtr.Zero,text,caption,0);
    }

  4. Do not suppress unmanaged code access via
    SuppressUnmanagedCodeSecurityAttribute.

  5. Do not use/UnsafeSwitch of tlbimp.exe. Wrap the RCW in managed code so that you
    Can assert and demand permissions declaratively on the wrapper.

  6. On server machines, deploy a code access security policy that
    Grants only Microsoft, ECMA, and self (identified by a strong name) full trust.
    Code originating from anywhere else is implicitly granted nothing.

  7. On client machines, deploy a security policy that grants client
    Application only the permissions to execute, to call back the server, and
    Potentially display user interface. When not using ClickOnce, client application
    Shocould be identified by a strong name in the code groups.

  8. To counter a luring attack, always refuse at the assembly level
    All permissions not required to perform the task at hand:

    [assembly:UIPermission(SecurityAction.RequestRefuse,
    Window=UIPermissionWindow.AllWindows)]

  9. Always set the principal policy in everyMain ()
    Method to Windows:

    public class MyClass
    {
    static void Main( )
    {
    AppDomain currentDomain = AppDomain.CurrentDomain;
    currentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
    }
    //other methods
    }

  10. Never assert a permission without demanding a different
    Permission in its place.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.