我已经构建了一个程序来检查应用程序是否启用。如果启用,它将执行一个BackgroundWorker
,如果没有,它将通知用户并立即关闭。它适用于我的计算机,但对其他人来说,它无法无错误地完成代码。
这是我的代码:
Dim Status As String = ""
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
If Status = "Enabled" Or Status = "Disabled" Then
Else
Status = WebBrowser1.Document.GetElementById(Account & "Flag").InnerText.ToString
If Status = "Enabled" Then
BackgroundWorker1.RunWorkerAsync()
ElseIf Status = "Disabled" Then
MessageBox.Show("Disabled", "System", MessageBoxButtons.OK)
Close()
Else
Status = ""
End If
End If
End Sub
对我来说,我认为它不会启动BackgroundWorker
来完成它的工作。我通过在第一行代码后面放置 MsgBox("Code 1 Success")
和在第二行代码后面放置 MsgBox("Code 2 Success")
来测试代码代码等等。它到达了BackgroundWorker1.RunWorkerAsync()
代码,但它不执行BackgroundWorker下的代码。
这是BackgroundWorker1代码:
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Label1.Text = "Status: Checking"
Label1.ForeColor = Color.FromKnownColor(KnownColor.Highlight)
Try
Dim mysqlconnection As MySqlConnection = New MySqlConnection("server=85.10.205.173;port=3306;username='" & User & "';password='" & Pass & "'")
Dim mysqlcommand As MySqlCommand = Nothing
Dim mysqldatareader As MySqlDataReader = Nothing
mysqlconnection.Open()
Using table As DataTable = New DataTable
Using command As MySqlCommand = New MySqlCommand("Select * from login.accounts where Username = 'Jake';", mysqlconnection)
Using adapter As MySqlDataAdapter = New MySqlDataAdapter(command)
adapter.Fill(table)
End Using
End Using
For Each row As DataRow In table.Rows
If row("Flag") = "enable" Then
Label1.Text = "Status: Enabled"
Label1.ForeColor = Color.Green
Button1.Enabled = False
Button2.Enabled = True
ProgressBar1.Visible = False
Else
Label1.Text = "Status: Disabled"
Label1.ForeColor = Color.OrangeRed
Button1.Enabled = True
Button2.Enabled = False
ProgressBar2.Visible = False
End If
Next
End Using
mysqlconnection.Close()
Catch ex As Exception
Threading.Thread.Sleep(1000)
Label1.Text = "No Internet Connection"
End Try
End Sub
我知道它不会到达此代码,因为 Label1.Text
没有更改,如果它到达这部分代码,它一定是“状态:正在检查”。
我的代码有什么问题?再说一遍,它在我的计算机上有效,但对其他人却无效。非常感谢任何帮助!
最佳答案
根据 MSDN,
You must be careful not to manipulate any user-interface objects in your DoWork event handler. Instead, communicate to the user interface through the BackgroundWorker events.
可能是第一行导致了错误。最好在 UI 线程上调用它。请参阅How to: Make Thread-Safe Calls to Windows Forms Controls
旁注:
- 您在
DoWork
中的循环似乎不正确。您正在寻找行中的标志并设置启用和禁用状态,如果多行设置或未设置标志怎么办?如果查询每次只返回 1 行,那么您不需要此处的循环 - 您应该在
DoWork
事件处理程序中进行一些日志记录,以便了解内部实际发生的情况。 - 通常我们不会在
DoWork
事件处理程序中处理异常,而是使用RunWorkerCompleted
事件来告诉您流程中是否发生了任何异常。无论如何,最好使用此事件来了解该过程已完成。
关于mysql - 程序无法在不同设备上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39543534/