Link to home
Start Free TrialLog in
Avatar of bwz
bwz

asked on

use lock in thread

hi,

i want to use Interlocked in a function that called from a thread,
to prevent case that two threads will run at the same time.
this is my code:

    Public Sub Process1()
        If Threading.Interlocked.Exchange(UsingResorce, 1) = 0 Then
            iLog = New Log(iProgramName, iDeleteLogAfterDef)
            iLog.WriteToLog("Hello From process 1 " & Now)
        End If
    End Sub

the process1 fun called from this:

    Private Sub OnTimer(ByVal State As Object)
        Dim iMessageCenter As New MessageCenter
        Dim UsingResorce As Integer
        Select Case m_ThreadProcessNum
            Case eThreadProcess.Process1
                iMessageCenter.Process1()
            Case eThreadProcess.Process2
                iMessageCenter.Process2()
        End Select

and the thread call to onTimer like this (i'm use threading.timer):

            Dim callback As New Threading.TimerCallback(AddressOf OnTimer)

            myTimer = New Threading.Timer(callback, Nothing, 0, period)

i'm using it but it's not work , what can i do

thank's
Avatar of amyhxu
amyhxu

I don't understand -- if you don't want two threads run at the same time, why not just use one thread? Can you explain why you use two threads in this case?
Is it because you want to use threading.timer? Then you can change that to the timer you can find in the toolbox.
Avatar of bwz

ASKER

i need to use two thread for differenct cases
that run at the same time but not clash between them
(one reason is that i use the same log file in the threads and only one can write to the file
any time).
i hope it was more clear.

thank's
ASKER CERTIFIED SOLUTION
Avatar of nachiket
nachiket

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial