Thread safe variable in VB.NET

sony picture sony · Oct 12, 2010 · Viewed 10.5k times · Source

Is this the right way of declaration dbreaders when mulitple users access the same page?

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

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

What would be the best practice to make the dbReader thread safe in VB.Net?

Does declaring them as static makes it thread safe?

Thanks in Advance,

Answer

Alex Essilfie picture Alex Essilfie · Oct 12, 2010

If you'd like each thread to modify the variable without 'fear' another thread will change it somewhere along the line, it is best you adorn the variable with the ThreadStatic attribute.

The ThreadStatic attribute creates a different instance of the variable for each thread that's created so you're confident there won't be any race conditions.

Example (from MSDN)

Imports System
<ThreadStatic> Shared value As Integer