VB.net使用扩展方法避免跨线程异常 [英] VB.net avoiding cross thread exception with extension method
问题描述
你好 我正在尝试实现一种无需使用委托即可更新表单控件的解决方案.
Hello I am trying to implement a solution for updating form controls without using a delegate.
我正在尝试使用此页面上的第一种解决方案:
I am attempting to use the 1st solution on this page:
http://www.dreamincode.net/forums/blog/143/entry-2337-handling-the-dreaded-cross-thread-exception/
Imports System.ComponentModel
Imports System.Runtime.CompilerServices
Public Module MyInvoke
<Extension()> _
Public Sub CustomInvoke(Of T As ISynchronizeInvoke)(ByVal control As T, ByVal toPerform As Action(Of T))
If control.InvokeRequired Then
control.Invoke(toPerform, New Object() {control})
toPerform(control)
End If
End Sub
End Module
该网站以使用方式为例:
The site gives this as example of how to use:
Label1.CustomInvoke(l => l.Text = "Hello World!")
但是我得到的'l'没有被声明为错误. 如您所见,这对VB或任何OOP来说都是很新的东西.
But i get 'l' is not declared error. As you can see im very new to VB or any OOP.
我可以在该页面上使用工作台上的第二个解决方案(使用委托),但是我在该线程中有很多工作要做,似乎我需要为每件事编写一个新的委托子,这似乎很浪费
I can get the second solution on that page to work (using delegates) but i have quite a few things to do in this thread and it seems like i would need to write a new delegate sub for each thing, which seems wasteful.
我需要做的是从组合框中选择第一个项目,用选定的项目更新textbox.text,然后将选定的项目传递给函数. 然后等待x秒,然后重新开始,选择第二项.
What i need to do is select the 1st item from a combobox, update a textbox.text with the selected item, and pass the selected item to a function. Then wait for x seconds and start again, selecting the second item.
我可以让它在单线程应用程序中工作,但是我需要接口保持响应.
I can get it to work in a single threaded application, but i need the interface to remain responsive.
任何帮助都将不胜感激.
Any help greatly appreciated.
好的,因此更改语法适用于该示例. 但是,如果我将其更改为
OK so changing the syntax worked for the example. However if i change it from
Label1.CustomInvoke(Sub(l) l.text = "hello world!")
(效果很好):
Dim indexnumber As Integer = 0
ComboBox1.CustomInvoke(Sub(l) l.SelectedIndex = indexnumber)
我收到跨线程错误,好像我什至没有使用此方法一样:
I get a cross threading error as though i didnt even use this method:
Cross-thread operation not valid: Control 'ComboBox1' accessed from a thread other than the thread it was created on.
所以现在我回到我的起点了吗? 非常感谢任何帮助.
So now im back to where i started? Any further help very much appreciated.
推荐答案
第二期;我认为您需要添加其他内容:
Per your second issue; I think you need to add an Else:
Public Sub CustomInvoke(Of T As ISynchronizeInvoke)(ByVal control As T, ByVal toPerform As Action(Of T))
If control.InvokeRequired Then
control.Invoke(toPerform, New Object() {control})
Else
' ^^^^
toPerform(control)
End If
End Sub
这篇关于VB.net使用扩展方法避免跨线程异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!