VB.net避免与扩展方法的交叉线程异常

问题描述:

你好 我想实现一个解决方案来更新表单控件而不使用委托。VB.net避免与扩展方法的交叉线程异常

我试图使用此页面上的第一个解决方案:

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 

该网站给出这个作为例子说明如何使用:

Label1.CustomInvoke(l => l.Text = "Hello World!") 

,但我得到' l'没有声明错误。你可以看到我对VB或任何OOP都很陌生。

我可以得到第二个解决方案在该页面上工作(使用委托),但我有很多事情要做在这个线程中,好像我需要为每个东西写一个新的委托子,这似乎浪费。

我需要做的是从组合框中选择第一项,使用所选项更新textbox.text,并将所选项传递给函数。 然后等待x秒钟并重新开始,选择第二个项目。

我可以让它在单线程应用程序中工作,但我需要接口保持响应。

任何帮助非常感谢。

编辑: 确定,以便更改为该示例工作的语法。 但是如果我改变它从

Label1.CustomInvoke(Sub(l) l.text = "hello world!") 

(这只是正常工作)到:

Dim indexnumber As Integer = 0 
ComboBox1.CustomInvoke(Sub(l) l.SelectedIndex = indexnumber) 

我得到一个跨线程错误,就像我没有,甚至使用此方法:

Cross-thread operation not valid: Control 'ComboBox1' accessed from a thread other than the thread it was created on. 

那么现在我回到我开始的地方? 任何进一步的帮助非常感谢。

+0

谢谢,愚蠢的错误在那里。 – Steve 2011-01-13 20:33:25

您的第二个问题;我认为你需要添加一个其他的:

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 
+0

谢谢,就是这样。真的应该注意到了。至少在学习一些东西! – Steve 2011-01-13 20:56:12

令人困惑的VB和C#语法。你拉姆达(几乎,缺少大括号)有效的C#,但在VB中你必须写这个是不同的:

Label1.CustomInvoke(Sub (l) l.Text = "Hello World!") 

是的,这句法S *中正。抱歉。 :-(

Label1.CustomInvoke(L => l.Text =的 “Hello World!”)

这是C#语法

的VB.NET等效为:

Label1.CustomInvoke(Sub(l) l.Text = "Hello World!") 

...不使用委托更新表单控件...

只是FYI - 一个lambda表达式,这正是使用,是一种委托形式。这只是用于声明和定义委托的更方便的语法 - 但您仍然在此处使用委托。