我已经解决了这个问题,我使用backgroundWorker
检查数据库是否 OPEN
,这是我的代码:
Public Class Form1
Delegate Sub SetLabelText_Delegate(ByVal [Label] As Label, ByVal [text] As String)
Dim sqlconnection As New SqlConnection("Data Source=" & My.Settings.Server & ";Initial Catalog=" & My.Settings.Database & ";Integrated Security=false;user id=" & My.Settings.Username & ";password=" & My.Settings.Password & ";Connection Timeout=5;")
Dim connectionStatus As String
Private Sub SetLabelText_ThreadSafe(ByVal [Label] As Label, ByVal [text] As String)
If [Label].InvokeRequired Then
Dim MyDelegate As New SetLabelText_Delegate(AddressOf SetLabelText_ThreadSafe)
Me.Invoke(MyDelegate, New Object() {[Label], [text]})
Else
[Label].Text = [text]
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'I store my database information to my.settings then display it on textboxes for manipulation
TextBox1.Text = My.Settings.Server
TextBox2.Text = My.Settings.Database
TextBox3.Text = My.Settings.Username
TextBox4.Text = My.Settings.Password
'just getting my computer name
lblCompName.Text = System.Windows.Forms.SystemInformation.ComputerName
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Try
If sqlconnection.State = ConnectionState.Closed Then
sqlconnection.Open()
connectionStatus = "Online"
'sqlconnection.Open()
SetLabelText_ThreadSafe(Me.Label1, "Database Status: online")
End If
Catch ex As Exception
connectionStatus = "Offline"
sqlconnection.Close()
SetLabelText_ThreadSafe(Me.Label1, "Database Status: offline")
End Try
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Error IsNot Nothing Then
Label1.Text = "Database Status: " & connectionStatus
Else
Label1.Text = "Database Status: " & connectionStatus
End If
BackgroundWorker1.RunWorkerAsync()
End Sub
end class
在上面的代码中,它确实有效,它在Visual Studio中重新启动程序时会显示" database is online/offline
" ,但是当我运行该程序时关闭/禁用我的网络连接(我的数据库在其他计算机上)它始终显示 "Database is ONLINE"
,但我很确定我的电脑和数据库之间已经没有连接(因为我PING
)因此必须显示为 "Database is oFFLINE"
。
我是否错过了使用 backgroundWOrker
的相关信息?哦顺便说一下,我是 BackgroundWorker
的新手。
非常感谢任何帮助或替代解决方案,谢谢!