Potential Variable in VB.NET

Is this the correct way to declare dbreaders when mulitple users access the same page?

public dbReader as system.Data.IDataReader at the class level or

Dim dbReader as System.Data.IDataReader in each function inside the class.

What would be the best practice for securing the dbReader stream in VB.Net?

Does they declare them as static, makes it thread safe?

Thanks Advance,

+4
source share
3 answers

If you want each thread to change a variable without fear, another thread changes it somewhere along the line, it’s best to decorate the variable with ThreadStatic .

The ThreadStatic attribute creates another instance of the variable for each thread created, so you are sure that there will be no race conditions.

Example (from MSDN)

 Imports System <ThreadStatic> Shared value As Integer 
+3
source

I would recommend you use reentrant functions when possible, which by definition are thread safe, instead of using class fields:

 Function GetIds() As IEnumerable(Of Integer) Dim result = New List(Of Integer)() Using conn = New SqlConnection("SomeConnectionString") Using cmd = conn.CreateCommand() conn.Open() cmd.CommandText = "SELECT id FROM foo" Using reader = cmd.ExecuteReader() While reader.Read() result.Add(reader.GetInt32(0)) End While End Using End Using End Using Return result End Function 
+1
source

If you use a Dim variable in a function, no other thread can access this variable, making it thread safe by definition.

However, if you declare it at the class level, you can use SyncLock , which will prevent other threads from accessing it if it is currently being used by others.

Example:

 Public Sub AccessVariable() SyncLock Me.dbReader 'Work With dbReader End SyncLock End Sub 
+1
source

All Articles