how to create class that only 1 thread can access it in MT app.

  • Thread starter Thread starter Daylor
  • Start date Start date
D

Daylor

hi.
i have multi thread application in vb.net

is there a way NET support, so i can mark the class , to be access
only for 1 thread each time ?

if there is , small sytax sample will help

//what i need to add , so only 1 thread per time can access this class in
MultiThread app.
public MySharedClass

End Class
 
No, you will have to manually synchronize all code that needs to be
protected in this way.
 
Daylor,
As Marina suggested you need to manually do this.

I normally do something like:
public Class MySharedClass

Private Readonly m_padlock As New Object()

Private m_value1, m_value2 As String

Public Sub New(ByVal value1 As String, ByVal value2 As String)
m_value1 = value1
m_value2 = value2
End Sub

Public Sub Method1(ByVal value1 As String)
SyncLock m_padlock
If m_value1 <> value1 Then
m_value1 = value1
End If
End SyncLock
End Sub

Public Sub Method2(ByVal value2 As String)
SyncLock m_padlock
If m_value2 <> value2 Then
m_value2 = value2
End If
End SyncLock
End Sub
End Class

The m_padlock variable acts as the gate to the class, each method tries to
lock the gate (SyncLock) while the thread is "inside" the class.

For further details see:

http://msdn.microsoft.com/library/d...us/vbcn7/html/vaconThreadingInVisualBasic.asp


Hope this helps
Jay
 
well the problem is more than that ,
what if my shared class has form in it.

i read that the thread that create the form, should call his methods.

does NET has simple way to call async way to do that ?
(i think when you use delegate , a thread from thread pool is used , in my
case i need
the thread that created the form to call his methods.)

its seems to be very basic issure, cause in alot of multi thread
applications
you have forms.

what is the way to call form in multithread app ?
 
Daylor,
well the problem is more than that ,
what if my shared class has form in it.
As some would say: This changes every thing! ;-)

For a form, to ensure that a "method" is executed on the thread that created
the Win32 handle, you need to use the Control.Invoke method. Closely related
to this method is Control.BeginInvoke, Control.EndInvoke, and
Control.InvokeRequired.
does NET has simple way to call async way to do that ?
(i think when you use delegate , a thread from thread pool is used , in my
case i need
the thread that created the form to call his methods.)
Only if you did BeginInvoke on the delegate, remember the thread where the
async method is running needs to use Control.Invoke to call into your Form,
however the Form (Main Thread) is free to call into any object, even if that
object can also be modified by the thread where the async method is running,
then you need to use the SyncLock statement I gave.

If that made sense.

I thought this was all covered in the link I gave...

Hope this helps
Jay
 
Back
Top