如何通知调用sub QueueUserWorkItem sub完成?

时间:2014-12-03 21:01:55

标签: vb.net multithreading

timerTicks每秒触发一次,只要CheckTableForNewRecords运行子IsCheckingTable = False

Sub CheckTableForNewRecords确定我的SQL表是否有新记录,如果有,它将在新线程上运行sub SQL.GetTrades

仅当线程子IsCheckingTable完成时,我才需要将属性False更改为SQL.GetTrades

我该怎么做?

Public Sub timerTicks() Handles EventTimer.Tick
    If IsCheckingTable = False Then
        CheckTableForNewRecords()
    End If
    Timertxt.Text = Date.Now
End Sub

Public Sub CheckTableForNewRecords()
    sw.Restart()
    sw.Start()
    IsCheckingTable = True
    PR = LR
    SQL.GETlastrcrd(QueryLR, LR)
    NR = LR - PR
    LastrcrdFRM.Text = LR
    PrvLastrcrdFRM.Text = PR
    NewRecordsFRM.Text = NR
    'check table
    If NR > 0 Then
        Dim QueryRR As String = "SELECT * from(select ROW_NUMBER() over (Order by StreamingID ) as row, " & _
                                "StreamingID,WatchlistID,symbol,Bid,Ask,Last,High,Low,PrevClose,Volume,TradeTime," & _
                                "QuoteTime,TradeDate,QuoteDate,Volatility,OpenInterest,UnderlyingSymbol,CallPut,TradeVolume,TradeAmount,Trade,LastSize from optionstream) " & _
                                "as StreamingID where StreamingID between " & PR & " AND " & LR
        Threading.ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf SQL.GetTrades), QueryRR)
    End If
    IsCheckingTable = False
    TEchecktradesFRM.Text = sw.ElapsedMilliseconds
End Sub

1 个答案:

答案 0 :(得分:0)

假设你不关心线程安全或任何事情,你可以这样做的一种非常天真的方式是:

ThreadPool.QueueUserWorkItem(
    Sub() 
        SQL.GetTrades()
        IsCheckingTable = True
    End Sub)

您可能希望根据here描述的原因标记IsCheckingTable volatile。您可能还需要QueueUserWorkItem内的try / catch / finally,以确保我们重置IsCheckingTable

但正如SLaks评论的那样,使用较新版本.NET中的任务可能更适合您尝试做的事情。不幸的是,我对它们还不是很熟悉。