Search:

MFSD
knowledge base

Navigation

FrontPage

RecentChanges

FindPage

HelpContents

GUI Editor Test
Page

Page

Edit (Text)

Info

Subscribe

Add
Link

Attachments

More Actions: Raw Text Print View Delete Cache
------------ Check Spelling Like
Pages Local Site Map ------------ Rename Page Delete
Page ------------ Attach
File Despam My
Pages Package Pages Render As Docbook Subscribe User

User

OwenJones

UserPreferences

Recently viewed pages

Plausibilit...yntax
Guide

Macros

Macros

formatters

parsers

The
wiki - ...pers' notes

Wiki setup
notes

visio test
page

FrontPage

Owen's
Ebeers ToDo list

VB coding
standards

GUI
Editor Test Page

MoinMoin Powered

Python Powered

Valid HTML 4.01

GUI
Editor Test Page

Coding Standards for .NET using
VB Author : Paul RussellDate : Nov 28th
2005Reference : MFSD_DOCS_93496_1Version : 1Revision : 1Status : Draft Summary
: The purpose of this document is to present a set of common rules and
recommendations for developing applications using Microsoft VB.NET. By
defining guidelines, an ISTD consistency of style, formatting and convention
can be applied to each new project making development and post implementation
support simpler. This document is based on MSD_DOCS_116811_2 (Coding Standards
for .NET using C#).

AMENDMENTS HISTORY
||Version||<^width="84px"style="BORDER-RIGHT:
#ece9d8; PADDING-RIGHT: 5.4pt; BORDER-TOP: #ece9d8; PADDING-LEFT: 5.4pt;
PADDING-BOTTOM: 0in; BORDER-LEFT: #ece9d8; WIDTH: 63pt; PADDING-TOP: 0in;
BORDER-BOTTOM: #ece9d8; BACKGROUND-COLOR:
transparent">Revision||<^width="96px"style="BORDER-RIGHT:
#ece9d8; PADDING-RIGHT: 5.4pt; BORDER-TOP: #ece9d8; PADDING-LEFT: 5.4pt;
PADDING-BOTTOM: 0in; BORDER-LEFT: #ece9d8; WIDTH: 1in; PADDING-TOP: 0in;
BORDER-BOTTOM: #ece9d8; BACKGROUND-COLOR: transparent">Edited
By||<^width="309px"style="BORDER-RIGHT: #ece9d8; PADDING-RIGHT:
5.4pt; BORDER-TOP: #ece9d8; PADDING-LEFT: 5.4pt; PADDING-BOTTOM: 0in;
BORDER-LEFT: #ece9d8; WIDTH: 231.7pt; PADDING-TOP: 0in; BORDER-BOTTOM: #ece9d8;
BACKGROUND-COLOR: transparent">Comment||

1

0

Paul Russell

Initial Draft – based on MSD_DOCS_116811_2 (v2.0)

1

1

Paul Russell

Edited of examples for consistency.Corrections for VB.NET 2005
content.Changed text of hyperlinks to display friendly description instead
of URL.

TABLE OF CONTENTS 1.
INTRODUCTION. 42.
DOCUMENT CONVENTIONS. 43.
NAMING CONVENTIONS. 44.
APPLICATION OF NAMING CONVENTIONS. 65.
CODE STYLE. 96.
CODE COMMENTING. 107.
CODING GUIDELINES. 117.1
General117.2
Variables and Types117.3
Flow Control117.4
Exception Handling. 127.5
Object Composition. 137.6
Events and Delegates157.7
Threading. 15

The intention of this document is to describe a set of
standards and guidelines that are to be used for new development projects using
Microsoft VB.NET. These represent a combination of general best practice coding
styles and the conventions used by Microsoft. The goal of the standard is to
make development and support of VB.NET systems simpler and more consistent
across projects. The standard is not complete in the sense that all standards
documents should evolve with experience and changes in the technology. It is not
anticipated that these guidelines will be retrospectively applied to existing
systems. It is the responsibility of developers to understand, be familiar with
and follow these standards. Any of the standards may be challenged at any time,
but until such challenges have been made and resolved, developers should conform
to the current standards. The process for challenging the standard or requesting
new standards will be documented on the WebSig. The standards contained in this
document are based on, and should shadow any changes to, document
MSD_DOCS_116811_2 (Coding Standards for .NET using C#). The
following conventions are used in throughout this document to indicate that
rules should apply in a hard or softer way: ||Always||<^width="489px"style="BORDER-RIGHT:
#ece9d8; PADDING-RIGHT: 5.4pt; BORDER-TOP: #ece9d8; PADDING-LEFT: 5.4pt;
PADDING-BOTTOM: 0in; BORDER-LEFT: #ece9d8; WIDTH: 366.7pt; PADDING-TOP: 0in;
BORDER-BOTTOM: #ece9d8; BACKGROUND-COLOR: transparent">This rule must be
enforced||

Never

This action must not happen

Do Not

This action must not happen

Avoid

It is desirable that the action does not happen although some
exceptions to this principle may exist

Try

The rule should be attempted where possible

Example

Illustrates a rule

Reason

Explains a rule

Where a rule (or part of a rule) only applies to VB.NET 2005, this is
indicated by a box surrounding the relevant section and the words "VB.NET
2005" in red to the left of the section.
||3.1||||||||<^width="527px"style="BORDER-RIGHT:
#ece9d8; PADDING-RIGHT: 5.4pt; BORDER-TOP: #ece9d8; PADDING-LEFT: 5.4pt;
PADDING-BOTTOM: 0in; BORDER-LEFT: #ece9d8; WIDTH: 395.1pt; PADDING-TOP: 0in;
BORDER-BOTTOM: #ece9d8; BACKGROUND-COLOR: transparent">Always use Camel
Case or Pascal Case. See section 4 for details where each model is
appropriate. ||

3.2

Avoid all upper case names. Single lowercase words are
acceptable.

3.3

Do not choose names that begin with numeric characters.

3.4

Use meaningful, descriptive and specific names.Be consistent when
choosing names e.g. Forename, FirstName.

3.5

Variables and properties should describe the entity not its attributes
such as type or size.

3.6

Do not use Hungarian notation.Example: Dim customerName As String
'GoodDim strCustomerName As String 'Bad!

3.7

Avoid using abbreviations unless the full name is excessively
large.Example:Dim bankAccount As Account 'GoodDim bnkct As Account 'Bad!
If abbreviations are used, apply the abbreviated name consistently.

3.8

Do not use reserved words as names.

3.9

Avoid conflicts with existing .NET framework namespaces or data types.

3.10

Try not to add superfluous prefixes or suffixes to identifiers.Example:
Dim customerId As Integer 'GoodDim ipCustomerId As Integer 'Bad! Public
Class Customer 'Good …End Class Public Class CCustomer 'Bad! …End Class
Try to avoid naming constructs such as myCustomer, thisCustomer when
dealing with instances of an object. Example:Public Sub PrintCustomer(BVal
myCustomer As Customer) 'Not so good …End Sub Public Sub
PrintCustomer(ByVal customer As Customer) 'Better? …End Sub

3.11

Avoid including parent class names within a property name where
possible.Example:Dim lastCustomer As StringlastCustomer = Customer.Name
'GoodlastCustomer = Customer.CustomerName 'Bad!

3.12

Try to prefix Boolean variables or properties with “Can”, “Has” or
“Is”.

3.13

Append computation qualifiers to variable names like Average,
Count.Example:Dim averageSalary As Long 'GoodDim average As Long 'Bad!

3.14

Collection classes should generally be named using the plural of the
constituent type name.Example:Public Class Customer …End Class Public
Class Customers Inherits CollectionBase …End Class Where the singular and
plural forms are identical, postfix with the word
collection.Example:Public Class TimeSeries …End Class Public Class
TimeSeriesCollection Inherits CollectionBase …End Class If in doubt, adopt
a name that will be most clearly understood in the context of the
business.Example:Dog and Dogs (if the more common business use is Dogs)Dog
and Pack (if the more common business use is Pack)

3.15

Always use a prefix when naming GUI controls. This makes it easier to
locate items with intellisense.

Checkbox

chk

Checked List Box

Lst

Combo Box

cbo

Context Menu

ctx

Control (generic)

ctl

Data Grid

grd

Domain up down

dom

Button

btn

Form

frm

Group Box

grp

Help Provider

hlp

Horizontal Scroll Bar

hsb

Image List or Image

img

Label

Lbl

Link Label

lnk

List Box

lst

List View

lvw

MDI child

mdi

Menu Item

mnu

Notify Icon

nfi

Numeric Up Down

num

Open File Dialog

opn

Panel

pnl

Progress Bar

prg

Radio Button

opt

Picture Box

pic

Rich Text Box

rtf

Save File Dialog

sav

Status Bar

sbr

Tab

tab

Text Box

txt

Timer

tmr

Tooltip

tip

Toolbar

Tbr

Track Bar

trk

TreeView

tre

Splitter

spl

Vertical Scroll Bar

Vsb

Naming conventions are applied to various project entities
as shown below ||4.1||<^width="120px"style="BORDER-RIGHT: #ece9d8;
PADDING-RIGHT: 5.4pt; BORDER-TOP: #ece9d8; PADDING-LEFT: 5.4pt; PADDING-BOTTOM:
0in; BORDER-LEFT: #ece9d8; WIDTH: 89.95pt; PADDING-TOP: 0in; BORDER-BOTTOM:
#ece9d8; BACKGROUND-COLOR: transparent">Project File
Name||<^width="405px"style="BORDER-RIGHT: #ece9d8; PADDING-RIGHT: 5.4pt;
BORDER-TOP: #ece9d8; PADDING-LEFT: 5.4pt; PADDING-BOTTOM: 0in; BORDER-LEFT:
#ece9d8; WIDTH: 303.7pt; PADDING-TOP: 0in; BORDER-BOTTOM: #ece9d8;
BACKGROUND-COLOR: transparent">Pascal CaseTry to match the Assembly Name and
Root Namespace.Example:Namespace BoE.CCBS.Events.ExampleAssembly
BoE.CCBS.Events.Example.dllProject ….\BoE\CCBS\Events\Example.vbproj Store the
project file in a directory structure that corresponds to the namespace
structure. ||

4.2

Source File Name

Pascal CaseAlways match the Class name with the file name.Do not
include multiple classes in a single file.

4.3

Resource File

Pascal CaseUse a descriptive filename.

4.4

Namespace

Pascal CaseTry to partially match the assembly name.

4.5

Class Name

Pascal CaseUse a noun or noun phrase for the class name.Try to add an
appropriate suffix when sub-classing from another type.Example:Public
Class ForecastItems …End Class Public Class PostCodeValidationEventArgs
Inherits EventArgs …End Class

4.6

Structure Name

Pascal CaseUse a noun or noun phrase for the class name.Try to add an
appropriate suffix when sub-classing from another type.Example:Public
Structure ApplicationConfiguration …End Structure

4.7

Interfaces

Pascal CaseAlways prefixed with I.Example:Public Interface IPrintable
…End Interface

4.8

Method

Pascal CaseTry to use a verb or verb-object pair for the
name.Example:Public Sub Execute() …End Sub Public Sub ExecuteCommand()
…End Sub Public Function GetCustomerAddress() As String …End Sub

4.9

Property

Pascal CaseUse a name that is representative of the entity being
returned. Do not prefix with Get or Set.Example:Public Property Name() As
String …End Property

4.10

Field(Public Protected or Friend)

Pascal CaseAvoid if possible. Access via properties.

4.11

Field (Private)

Camel Case and prefixed with an underscore.Example:Private _name As
String

4.12

Constant

Pascal Case

4.13

Enumeration

Pascal CaseExample:Public Enum CaseStatus Outstanding InProgress
Referred ClosedEnd Enum Additional Note:If bit masking is required, use
the FlagsAttribute. Make the identifying name plural when using the
FlagsAttribute.

4.14

Delegate or Event

Treat as a field with the relevant access modifier.Example:Public Event
LoadPlugin As EventHandler

4.15

Local Variable

Camel CaseAvoid using single character variables except in for
loops.Avoid enumerating variable names like text1, text2, text3.

4.16

Parameter

Camel CaseExample:Public Sub Execute(ByVal commandText As String,
_ByVal interationCount As Integer) …End Sub

4.17

Namespace Construction

Follow a standard pattern for namespace constructionBoE.[Business Area/
Project/Functional Area].[Application Name/Shared].[Logical
Layer/Technology].[Sub Grouping]
Example:BoE.CCIT.FoI.BusinessEntitiesBoE.Markets.FiguresChief.WebUI

||5.1||<^width="527px"style="BORDER-RIGHT: #ece9d8;
PADDING-RIGHT: 5.4pt; BORDER-TOP: #ece9d8; PADDING-LEFT: 5.4pt;
PADDING-BOTTOM: 0in; BORDER-LEFT: #ece9d8; WIDTH: 395.1pt; PADDING-TOP: 0in;
BORDER-BOTTOM: #ece9d8; BACKGROUND-COLOR: transparent">Always declare only
one namespace per file (see 4.1).Use the namespace convention described in
4.17. ||

5.2

Avoid including multiple top level classes in one file (see 4.1).
Nested class declarations are permissible.

5.3

Use a tab indentation size of 4. This may be set up in Visual Studio.

5.4

Declare variables independently using a separate line for each.

5.5

Place namespace “Imports” statements at the top of the file.Try to
group “Imports” statements so that System namespaces appear above custom
namespaces.Example:Imports System.WebImports System.TextImports
BoE.CCBS.Events

5.6

Group internal class implementation as follows:Member VariablesNested
Enumerations, Structures and ClassesConstructors and
DestructorsPropertiesMethods

5.7

Try to order declarations within the groups above (5.8) based upon
their access modifier:PublicProtectedFriendPrivate Only use other layouts
where clarity would be improved as a result.

5.8

Segregate Interface implementation using #Region statements. Use
comments on #End Region statements if this improves
clarity.Example:#Region "Public Interface" …#End Region 'Public Interface

5.9

Append the folder name to the namespace for source files residing in
sub folders.

5.10

Indent all code blocks contained within braces.

5.11

Use CRLF and tabs to separate and organise code.

5.12

Avoid declaring multiple attributes on the same line.
Example:<Attribute1, _Attribute2> _Public Class Customer …End Class

5.13

Avoid superfluous formatting such as additional spaces to line up
variable declarations.Example:Dim someVariable As Integer = 1 Dim
anotherVariable As StringBuilder = New StringBuilder()Dim
yetAnotherVariable As SomeVeryLongClassName = New
SomeVeryLongClassName()

||6.1||<^width="527px"style="BORDER-RIGHT: #ece9d8;
PADDING-RIGHT: 5.4pt; BORDER-TOP: #ece9d8; PADDING-LEFT: 5.4pt;
PADDING-BOTTOM: 0in; BORDER-LEFT: #ece9d8; WIDTH: 395.1pt; PADDING-TOP: 0in;
BORDER-BOTTOM: #ece9d8; BACKGROUND-COLOR: transparent">Allow VSS to track
changes to source files, when checking in source files use the VSS comments
field to add a summary description of the changes and include any references
to external documents or T-plan logs. Add detail comments in the code as
described in the other points of this section. ||

6.2

Use ' or .

6.3

Add comments only where they describe functionality or process that is
not obvious from looking at the code, or not covered in other
documentation such as sequence diagrams.

6.4

Avoid flowerboxing comments (adding superfluous formatting
characters).Example:'

' Begin Save Process'

||

6.5

Try to use the comment keywords where appropriate to make your comments
appear in the Visual Studio Task List. (See MSDN
for more information about task list keywords).Example:'UNDONE: Save
disabled, waiting for DB changes to be completed.'HACK: Temporary fix
until the Config reader is implemented.'TODO: Exception logging needed
here.

6.6

Always use VBCommenter comment blocks () for public, protected
and friend declarations.Avoid using comment blocks for private
declarations unless required for documentation generation for example.

6.7

Always include <summary> comments.Include <param>,
<return> and <exception> where appropriate.

6.8

Always add CDATA tags to comments which have embedded code or markup to
avoid encoding issues.Example:<example>Add the
following section to
“appSettings”<code><![CDATA[
<configuration> <appSettings> <add
key=”ExampleSetting” value=”ExampleValue”>
</appSettings>
</configuration>]]></code></example>

||||||

7.1.1

Do not omit access modifiers. Explicitly declare all identifiers with
the appropriate access modifier instead of allowing the default.

7.1.2

Avoid mutual references between assemblies.

7.1.3

Do not use the default assembly versioning scheme for COM Visible
assemblies as this may cause GUIDs to change and break client
interoperability. Increment AssemblyVersionAttribute manually in this
case.

7.1.4

Set ComVisibleAttribute to False for all assemblies. Selectively enable
the ComVisibleAttribute for individual classes.

7.2.1

Try to initialise variables where you declare them.Example:Dim counter
As Integer = 0

7.2.2

Use the simplest data type required e.g. use an Integer over Long
unless there is a requirement to store 64 bit numbers.

7.2.3

Try to use the CTS types in preference to the language type aliases to
achieve standardisation between VB.Net and C#.Example:Dim countThis As
System.Int32 'GoodDim countThat As Integer 'Bad!

7.2.4

Avoid using inline numeric literals (magic numbers) use constant or an
enumeration instead.

7.2.5

Avoid using inline string literals. Use constants, resources, registry
or configuration file entries instead.

7.2.6

Only use constants for simple types.

7.2.7

Avoid boxing and unboxing value types.Example:Dim count As Integer =
1Dim refCount As Object = count 'Implicit boxing operation… 'Do some
processingDim newCount As Integer = DirectCast(refCount, Integer)
'Explicit unbox operation

7.2.8

Prefer String.Format or StringBuilder over concatenation.

7.2.9

Do not compare strings to String.Empty. Compare by using String.Length=
0.

7.2.10

Avoid hidden string allocations in loops. Use String.Compare()
instead.Reason:Some string operations ToLower() involve temporary string
allocations

7.3.1

Avoid recursive methods where loops or nested loops would serve.

7.3.2

Avoid using For Each to iterate immutable value type collections.

7.3.3

Do not modify enumerated items within a For Each loop.

7.3.4

Avoid evaluating Boolean conditions against True or
False.Example:'Avoid this SyntaxIf IsValid = TrueThen …End If 'Use This
SyntaxIf IsValid Then …End If

7.3.5

Avoid complex compound Boolean evaluations.Example:'Avoid This SyntaxIf
(value>MedianValue) AndAlso Not (value=MeanValue) AndAlso
(stateChanged) Then …End If 'Preferred SyntaxDim isMedian As Boolean
=(value > MedianValue)Dim isMean As Boolean = Not (value =
MeanValue)Dim isStateChanged As Boolean =(stateChanged) If (isMedian
AndAlso Not isMean) AndAlso isStateChanged Then …End If

7.3.6

Use case statements (Select Case) for simple operations with parallel
conditional processing or for operations with more than 3 possibilities.
Include an Else case when using a case statement.

7.3.7

Prefer polymorphism over case statements to encapsulate complex
operations.

7.4.1

Do not use try catch blocks for controlling the flow of program
execution. Slightly Contrived Example:' Always attempts an insert and if a
violation occurs on the primary key' try an updateTry
InsertCustomer(….)Catch ex As PrimaryKeyViolationException
UpdateCustomer(….)End Try ' More explicit decision point and flow
controlTry If customer.IsNew Then InsertCustomer(…) Else UpdateCustomer(…)
End IfCatch ex As SqlException …End Try

7.4.2

Only catch exceptions that you are going to handle.

7.4.3

Use exception filters where possible.

7.4.4

Avoid re-throwing an exception. Allow it to bubble up the call stack
instead.

7.4.5

If re-throwing an exception omit the exception argument from the throw
statement so the original call stack is preserved.Example:'Correct –
Preserves the call stackTry …Catch ex As SqlException ThrowEnd Try
'Incorrect – Call stack is lostTry …Catch ex As SqlException Throw exEnd
Try

7.4.6

When throwing a new exception always pass the inner exception in order
to maintain the exception tree and inner call stack. Additional Notes·
Where throwing an exception across a trust boundary (e.g. from a
middle-tier to client) you may not want to pass the inner exception to
avoid potentially sensitive information about the application being
exposed. In such a case, the original exception should be logged somewhere
first, to aid diagnostics.· Serializing exception trees across boundaries
may be slow, so be pragmatic.

7.4.7

Use validation to avoid exceptions. Program defensively.

7.4.8

Avoid custom exception classes in favour of existing exception classes.

7.4.9 VB.NET2005

Where custom exceptions are necessary:Derive from
ExceptionnotApplicationException.Override ToString() to provide
serialization. Override String Widening operator to provide serialization.
Implement the following constructor overloads:Public Sub New() …End Sub
Public Sub New(ByVal message As String) …End Sub Public Sub New(ByVal
message As String, ByVal innerException As Exception) …End Sub

7.4.10

Always add an Application.ThreadException handler in windows forms
applications to catch any unhandled exceptions and close-down gracefully
after displaying a suitable message to the user. Otherwise, the default
exception message is displayed and the application will terminate
immediately.

7.4.11

Avoid swallowing exceptions. If this behaviour is desired, ensure
comments are added to justify the choices made.

7.5.1

Always declare types explicitly with a namespace to ensure global
uniqueness. e

7.5.2

Avoid declaring methods with more than 7 parameters. Consider
refactoring or using an object or structure to pass information instead.

7.5.3

Avoid using the Shadows keyword to hide members of a derived type.

7.5.4

Only use the MyBase keyword to invoke the base class constructor or
base implementation within an override.

7.5.5

Do not use the protected access modifier in classes declared as
NotInheritable.

7.5.6

Validate enumerated type variables before consumption when converting
from an Integer or name representation.Example:Dim statusCode As Integer =
21If Enum.IsDefined(GetType(CaseStatus), statusCode) Then …End If

7.5.7

Avoid overriding Equals and the Equality operator without good reason.
See 7.5.8 for some base guidelines.

7.5.8 VB.NET 2005

Guidelines for Implementing Equals and the Equality Operator (=): ·
Consider overriding Equals() on a Structure or other value type.·
Implement the GetHashCodemethod whenever you implement the Equals method.
This keeps Equals and GetHashCode synchronized. · Override the Equals
method any time you implement the IComparable
Interface. · Do not throw exceptions from the Equals or GetHashCode
methods. · Consider overriding the equality operator (=) on a Structure or
other value type.· Override the Equals method whenever you implement =,
and make them do the same thing. This allows infrastructure code such as
Hashtable
and ArrayList,
which use the Equals method, to behave the same way as user code written
using =. · You should consider implementing operator overloading for the
equality (=), not equal (<>), less than (<), and greater than
(>) operators when you implement IComparable.· Do not throw exceptions
from the equality operator (=). Further
Information:[http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconimplementingequalsoperator.asp
Guidelines for Implementing Equals and the Equality Operator (==)]

VB.NET 2005

Consider overriding the Widening operator when overriding
ToString().Further
Information:[http://msdn.microsoft.com/library/en-us/dnvs05/html/vboperatoroverloading.asp?frame=true#vboperatoroverloading_topic4
Operator Overloading in Visual Basic 2005]

7.5.19

Avoid Parameter Arrays. Use overloading instead or use a structure or
object to encapsulate the parameters you wish to pass. Reasons:· There’s
no enforceable limit to the number of arguments received in this way· If
multiple types need to be supported the parameter array must be typed as
object· Can only have one parameter array (params) per method signature·
Can’t specify out parameters· Object encapsulation is more extensible

7.5.10

Avoid public nested classes, structures and enums. They should only be
used internally and therefore declared protected or private. Some useful
guidance on when to use nested classes:Recommendations
on Nested Classes in Components

7.5.11

Always implement IDisposable in classes that use external resources:
Public Sub Dispose() Dispose(True) GC.SuppressFinalize(Me)End Sub
Protected Overloads Overridable Sub Dispose(disposing As Boolean) If
disposing Then 'Free managed objects End If 'Free unmanaged objectsEnd Sub

7.5.12 VB.NET 2005

Wrap instantiation of IDisposable() objects with a using statement to
ensure Dispose() is called automatically.Example:Using dbConnection As New
SQLConnection(_connectionString) …End Using

7.5.13

Always call Close() and/or Dispose() on objects that offer
it.

7.6 Events and Delegates

7.6.1

Always check delegate instances for Nothing before invocation.

7.6.2

Use EventHandler and EventArgs for simple events.

7.6.3

Derive a custom EventArgs class to provide additional data.

7.6.4

Use CancelEventArgs to give control to the subscriber.

Threading is a large and complex topic and solutions
should be carefully designed and programmed to avoid deadlocks and race
conditions. It is possible to get threading badly wrong leading to subtle
bugs that are very difficult to track down.

7.7.1

Prefer the Monitor type rather than SyncLock for fine grained
control.Reason:Supports defensive coding with TryEnter().

7.7.2

Do not lock value types.Example:Dim isDisposing As BooleanSyncLock
isDisposing 'BAD – Do Not lock value types (implicit boxing) …End SyncLock
Further Information:[http://www.haacked.com/archive/2005/04/12/2634.aspx
Threading Tips: Never Lock a Value Type. Never Lock "This"]

7.7.3

Do not lock the current instance despite the amount of documentation
from Microsoft demonstrating this solution. Example:SyncLock Me 'BAD …End
SyncLock Do not lock on a type.Example:SyncLock GetType(Customer) 'BAD
…End SyncLock Lock on a private variable instead.Example:SyncLock
GetType(somePrivateStaticObject) 'Good code! …End SyncLock Reasons:A full
discussion of the issues with these techniques is discussed below.A
Special Dr. GUI: Don't Lock Type Objects!

7.7.4

If all you need to do is increment, decrement an Int32 or Int64 value,
or set a 32-bit value (an Int32, Object or Single), use the Interlocked
class. Reason:This won't block your thread. It's operations are
special-cased by the CLR to be performed by an single CPU instruction, so
they can't be pre-empted by another thread half-way through.

7.7.5

Synchronising Data for Multithreading.A number of other synchronisation
mechanisms are discussed in these articles:Safe Thread
SynchronizationSynchronizing
Data for Multithreading

last edited 2005-12-05 10:08:41 by
OwenJones