将文本框更新为与backgroundworker不同的形式

时间:2018-06-27 17:50:35

标签: vb.net textbox backgroundworker

我有两种形式,即Form1和Newform。 Form1有两个按钮和一个文本框,Newform有其自己的文本框。我正在使用settext子集来调用backgroundworker中的委托子集来更新两种形式的文本框。

Form1中的文本框似乎正在更新,但是Newform中的文本框没有更新。

如果我想以其他形式更新文本框,是否缺少某些内容?

先谢谢了。

Imports System.Threading
Public Class Form1
Dim stopbit As Boolean
Dim TestingComplete As Boolean
Dim ReadValue As Double
Dim FinalValue As Double

Delegate Sub SetTextCallback(ByRef Txtbox As TextBox, ByVal Txt As String)

'Thread Safe textbox update routine
Private Sub SetText(ByRef Txtbox As TextBox, ByVal Txt As String)

    ' InvokeRequired required compares the thread ID of the
    ' calling thread to the thread ID of the creating thread.
    ' If these threads are different, it returns true.
    Console.WriteLine(Txtbox.InvokeRequired & "  textbox invokerequired")

    If Txtbox.InvokeRequired Then
        Try
            'MsgBox("inside settext")
            Txtbox.Invoke(New SetTextCallback(AddressOf SetText), Txtbox, Txt)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    Else
        Txtbox.Text = Txt
        Txtbox.Update()
    End If
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    newform.Show()
End Sub

Function ReadTemp() As Double
    ReadValue = ReadValue / 2
    Return ReadValue
End Function

Sub Test()
    Dim starttime As Integer
    Dim EllapsedTime As Integer
    Dim OldValue As Double = 0
    Dim NewValue As Double = 0
    Dim Difference As Double = 1
    Dim Margin As Double = 0.1

    stopbit = False
    starttime = My.Computer.Clock.TickCount
    Do
        Thread.Sleep(200)
        OldValue = NewValue
        NewValue = ReadTemp()
        Difference = Math.Abs(NewValue - OldValue)
        SetText(Me.TextBox1, Difference.ToString)
        SetText(newform.TextBox1, Difference.ToString)
        newform.Refresh()
        EllapsedTime = My.Computer.Clock.TickCount - starttime


    Loop Until EllapsedTime > 5000 Or stopbit = True ' Or Difference < Margin
    FinalValue = NewValue
    TestingComplete = True

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    BackgroundWorker1.RunWorkerAsync()
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    stopbit = True
End Sub

Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

    For i As Integer = 1 To 10
        ReadValue = 100000
        TestingComplete = False
        ThreadPool.QueueUserWorkItem(AddressOf Test)

        Do
            Thread.Sleep(200)
        Loop Until TestingComplete = True
        MsgBox("Final Value  " & FinalValue)
    Next

End Sub

结束班级

2 个答案:

答案 0 :(得分:1)

您的问题是由于您使用的是newform默认实例。在VB.NET中,默认表单实例是一项功能,使您可以通过其类型名称访问表单,而不必手动创建它的实例。

换句话说,它允许您执行以下操作:

newform.Show()
newform.TextBox1.Text = "Something"

...不是正确的方法,而是这样:

Dim myNewForm As New newform
myNewForm.Show()
myNewForm.TextBox1.Text = "Something"

上面,我们创建了一个名为newform的{​​{1}}的新实例。为了能够使用框架中的 most 个对象(包括表单),这是必需的。但是,VB.NET通过提供为您创建实例来简化此行为,这就是我的第一个示例中的操作。

这些默认实例的问题在于它们是特定于线程的,这意味着将为使用此行为的每个线程创建一个新实例。

因此您在执行操作时所引用的表单:

myNewForm

...与您在线程中引用的形式不同,因为在该线程中为此实例创建了一个新实例

newform.Show()

解决方案当然是自己创建实例,从而使您可以完全控制正在发生的事情:

'This is not the same "newform" as above!
SetText(newform.TextBox1, Difference.ToString)

作为旁注,您可以删除对Dim newFrm As New newform Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load newFrm.Show() End Sub ...your code... Sub Test() ...your code... SetText(newFrm.TextBox1, Difference.ToString) ...even more of your code... End Sub newform.Refresh()的呼叫。这些只是通过强制窗体和文本框重新绘制自身而导致不必要的开销,当您更改影响其内容/设计的任何属性时,此操作已经完成(因此,实际上是使它们重新绘制两次)。

此外,如果您要调用UI线程更简单,并且您正在使用Visual Studio / Visual Basic 2010 或更高版本 ,您可以改用lambda expressions代替常规代表。它们更易于使用,并允许您在线创建可以在UI线程上调用的整个方法。

为此,我编写了一个名为Txtbox.Update()的扩展方法,该方法可让您在UI线程上调用 any 方法/函数,并为您检查InvokeIfRequired()。它与您现在拥有的类似,仅适用于任何控件(不仅限于文本框),并具有lambda表达式,可让您在UI上运行所需的任何代码。

您可以通过将模块添加到项目(InvokeRequired)并将其命名为Add New Item... > Module来使用它。然后将以下代码放入其中:

Extensions

这允许您通过执行以下操作来调用任一行代码:

Imports System.Runtime.CompilerServices

Public Module Extensions
    ''' <summary>
    ''' Invokes the specified method on the calling control's thread (if necessary, otherwise on the current thread).
    ''' </summary>
    ''' <param name="Control">The control which's thread to invoke the method at.</param>
    ''' <param name="Method">The method to invoke.</param>
    ''' <param name="Parameters">The parameters to pass to the method (optional).</param>
    ''' <remarks></remarks>
    <Extension()> _
    Public Function InvokeIfRequired(ByVal Control As Control, ByVal Method As [Delegate], ByVal ParamArray Parameters As Object()) As Object
        If Parameters IsNot Nothing AndAlso _
            Parameters.Length = 0 Then Parameters = Nothing

        If Control.InvokeRequired = True Then
            Return Control.Invoke(Method, Parameters)
        Else
            Return Method.DynamicInvoke(Parameters)
        End If
    End Function
End Module

或通过执行以下操作来调用整个代码块:

Me.InvokeIfRequired(Sub() Me.TextBox1.Text = Difference.ToString())

答案 1 :(得分:0)

YourSubHere

Me.Invoke(Sub()
          Form1.Textbox1.text="some text1"
          Form2.Textbox2.text="some text2"
          End Sub)
End Sub

或者如果是一个班轮。

Me.Invoke(Sub() Form1.Textbox1.text="some text1")

根据您的需要,您可以仅调用某些控件,例如:

Textbox1.invoke(Sub() Textbox1.text="some text1")