【发布时间】:2013-11-11 19:57:46
【问题描述】:
我正在尝试制作一些检查 Xbox 用户名的东西,但我尝试使用计时器来执行此操作,这会滞后于它的 UI。所以我想我是用后台工作人员来做的,但是用不同的线程,调用 UI 引用对我来说并没有真正奏效。有什么帮助吗?
For i As Integer = 0 To ListBox1.Items.Count
Using Wc As New WebClient()
Try
Dim Xbox As String = String.Empty
Xbox = Wc.DownloadString("http://www.xboxgamertag.com/search/" & ListBox1.SelectedItem.ToString())
If Xbox.Contains("Online Status") Then
FlatAlertBox1.Text = "Gamertag " & ListBox1.SelectedItem.ToString & " is taken :("
FlatAlertBox1.kind = FlatAlertBox._Kind.Error
FlatAlertBox1.Visible = True
End If
Catch ex As Exception
FlatAlertBox1.Text = "Gamertag " & ListBox1.SelectedItem.ToString & " is not taken!"
FlatAlertBox1.kind = FlatAlertBox._Kind.Success
FlatAlertBox1.Visible = True
End Try
End Using
Next
ListBox1.SelectedIndex += 1
当我尝试运行它时,我得到:
System.Windows.Forms.dll 中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理
附加信息:跨线程操作无效:控件“ListBox1”从创建它的线程以外的线程访问。
如果有这个异常的处理程序,程序可以安全地继续。
上线: FlatAlertBox1.Text = "Gamertag " & ListBox1.SelectedItem.ToString & " is not taken!"
【问题讨论】:
-
如果您在 2012 年或 2013 年,那么您可以使用 async/await 异步执行 fetch 并停止它在不使用线程的情况下阻塞 ui 线程。
标签: vb.net multithreading background worker