1

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.

Eric
  • 958
  • 1
  • 11
  • 28

1 Answers1

0

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.

Dmitry Reznik
  • 6,812
  • 2
  • 32
  • 27
  • Will killing the thread create an unwanted result? I was thinking about trying this but I was worried about what happens on the SQL Server end of things. Does it kill the process on the SQL Server as well? I read this [article](http://sqlblog.com/blogs/linchi_shea/archive/2010/02/04/killing-a-sql-server-thread-don-t.aspx) about killing processes on SQL Server which may cause unwanted results. Would this cause a similar problem? – Eric Mar 28 '12 at 18:52
  • The article deals with sql server threads - killing them is harmful. Killing your application thread won't do any harm your sql server. Worst thing could happen - SQL connection will be lost - which will anyway, eventually. It has no way of killing sql server process since it is independent. – Dmitry Reznik Mar 29 '12 at 03:57