交叉线无法正常工作 [英] Crossthreading not working
本文介绍了交叉线无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码:
Hi,
This is my code:
Private Delegate Sub UpdateListInvoker(ByVal WhatToWrite As String)
Private Sub UpdateListBox(ByVal WhatToWrite As String)
If Form1.ListBox2.InvokeRequired Then
Form1.ListBox2.Invoke(New UpdateListInvoker(AddressOf UpdateListBox), WhatToWrite)
Else
Form1.ListBox2.Items.Add(WhatToWrite)
End If
End Sub
使用:UpdateListBox(你好)
它只是没有做任何事情。为什么?
-Rixterz
To use: UpdateListBox("Hello")
It just isn't doing anything. Why?
-Rixterz
推荐答案
好的,所以看起来你试图调用一个委托form1来自你项目中的另一种形式,当我测试那个(而不是从form1开始的线程)时,我遇到了同样的问题。
你需要对后台线程(或来自form2)的form1进行引用。这是我在快速测试应用程序中工作的方式(在form2上调用form1上的委托):
试试这个:
Ok, so it looks like your trying to invoke a delegate on form1 from a different form in your project, and when I tested THAT (as opposed to a thread started from form1), I had the same problem you did.
You need to make a refrence to form1 available to the background thread (or from form2). This is how I got it to work (calling a delegate on form1 from form2) in my quick test app:
Try this:
' Form1 code:
' Define your delegate:
Public Delegate Sub UpdateListInvoker(ByVal whatToWrite As String)
' Create your reference object:
Public UpdateListBox As UpdateListInvoker
' Your callback:
Public Sub ListBoxUpdater(ByVal WhatToWrite As String)
If Me.InvokeRequired Then
Me.Invoke(UpdateListBox, WhatToWrite)
Else
Me.ListBox2.Items.Add(WhatToWrite)
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
UpdateListBox = AddressOf ListBoxUpdater
Form2.f1 = Me
Form2.Show()
End Sub
' Form2 code:
Public f1 As Form1
Private Sub bgThread()
' Elsewhere in your code...
f1.UpdateListBox("what you're adding to the listbox")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim t As New Threading.Thread(AddressOf bgThread)
t.Start()
End Sub
你看到在form2中,当我点击一个按钮时,我正在启动后台线程,然后从后台线程我正在使用它的参考更新form1上的列表框(f1)。
这应该适合你。
-Pete
You see that in form2, I'm starting a background thread when I click a button, and then from the background thread I'm updating a listbox on form1 by using it's reference (f1).
This should do the trick for you.
-Pete
这篇关于交叉线无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文