简体   繁体   中英

Access a running background thread VB.NET VS2008

I created a background thread that get's data and returns it to the main thread; this works. Now I want to be able to stop the SQL request from the main thread (probably on a button click).

This is my test code for creating the thread (working):

Private Sub GetSql()
    If (Me.InvokeRequired) Then
        Me.Invoke(New GetSqlDelegate(AddressOf GetSql))
    Else
        Dim da As SqlDataAdapter = New SqlDataAdapter("select * from database", _
            New SqlConnection(connectionString))
        dt = New DataTable
        da.Fill(dt)
        Me.BeginInvoke(New BindDataToGridDelegate(AddressOf BindDataToGrid))
    End If
End Sub

Private Delegate Sub BindDataToGridDelegate()
Private Sub BindDataToGrid()
    DataGridView1.DataSource = dt
    dt = Nothing
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    thrGetData = New Thread(AddressOf ThreadBackgroundData)
    thrGetData.IsBackground = True
    thrGetData.Start()
End Sub

How can I access the background thread to stop the query on demand?

Do I need to set a flag on the main thread telling the background thread to stop running then have the background thread poll the main thread at intervals?

Any help would be appreciated. I was trying to look for an example but I wasn't able to find a good one. Even pseudo code would help

Thanks.

DataAdapter.Fill method is synchronous, meaning it blocks current thread until it is completed. Basically, that means you can't add polling/checking in the background thread since everything it can do is execute Fill method (which may be time-consuming).

If your problem is stopping the operation itself (please note that no data may be returned), you should just call thread.Abort() from your main thread. For that you'd need to save thrGetData as class-level variable. More about Thread.Abort() may be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM