Search code examples
vb.netformsdispose

Checking if form closed from backgroundworker VB.NET


I have a few tasks for my backGroundWorker.The code is as follows:

     Private Sub bgworker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgworker.DoWork
    connecttosrv.showDialog
    Dim p() As Process
    p = Process.GetProcessesByName("mssqlserver")
    If p.Count > 0 Then
    Else
        Try
            Dim p1 As Process
            p1 = Process.Start("cmd.exe", "/C net start mssqlserver")
            p1.WaitForExit()
        Catch ex As Exception
            err = ex.ToString
        End Try
    End If
     Dim con As New SqlConnection("Data source=" & My.Settings.IP & "," & My.Settings.Port & ";Network Library=DBMSSOCN;initial catalog=offpodb;User id=" & My.Settings.username & ";Password=" & My.Settings.password & ";")
        con.open

Now let me explain my scenario . As u can see, the bgWorker tries to connect to my database using IP,Port,Username and Password that are stored in MY.SETTINGS.

The values of My.Settings.IP,Password,Usernmae,Port are all empty on startup.Their values get added from another form(connecttosrv in this case,this form has textboxes where user enter IP,Port,Password,Username).

Look at the bgWorker's code.The first line is :

 connecttosrv.ShowDialog

The other codes are executed after ConnectToSrv has showed.But as mentioned,bgWorkder tries to connect to the database getting required details from My.Settings , and My.Settings gets the values from ConnectToSrv form. So, as per my code, the bgWorker will execute other codes after it's done showing the ConnectToSrv form.This will cause the SQLCONNECTION to fail to connect as MY.SETTINGS values will be empty.

So the help i want can be said as either :

1• Is there anyway to make the BackGroundWorker check if ConnectToSrv form has closed so that My.Settings gets all required values for SQL Connection

or

2• Is it possible to pause the backgroundWorker when the 2nd form(ConnectTOSrv) has showed and resume it again when the form has closed. (After doing a bit of research, i found that i can set-up the BgWorker to check if Form IsDisposed but i don't know how to use/apply it)


Solution

  • When using Form.ShowDialog, the code after it wouldn't be executed until the form is closed. I think it's not the case with a BackgroundWorker.

    Try calling connecttosrv.ShowDialog() exactly before bgworker.RunWorkerAsync, so the code in bgworker_DoWork -which is the event raised when RunWorkerAsync is called- woudln't be executed until that dialog is closed.