跨线程问题,调用?

时间:2017-09-21 15:13:01

标签: vb.net multithreading

我一直在网上搜索,似乎找不到适合我错误的修补程序:'Handler to handle screen resizes! (Tablet being flipped etc...) Private Sub TouchRadio_Resize(sender As Object, e As EventArgs) Handles Me.Resize Dim thread As New Thread(AddressOf resizescreen) thread.Start() End Sub Public Sub resizescreen() System.Threading.Thread.Sleep(1) For index As Integer = 1 To 50000 If Screen.PrimaryScreen.Bounds.Width = (Screen.PrimaryScreen.Bounds.Width + 17) Then Exit For End If Dim screenWidth As Integer = Screen.PrimaryScreen.Bounds.Width screenWidth = (screenWidth + 17) Dim screenHeight As Integer = Screen.PrimaryScreen.Bounds.Height Me.Size = New System.Drawing.Size(screenWidth, screenHeight) 'Here it errors at GeckoWebBrowser1.Size = New System.Drawing.Size(screenWidth, screenHeight) Me.Location = New Point(0, 0) Next End Sub

我看了一下但却无法弄清楚我是如何调用我的尺寸变化的?

我的代码有效,而另一个抛出上面的代码是:

{{1}}

1 个答案:

答案 0 :(得分:1)

你可以使用这个小帮手。

Public Shared Sub InvokeIfRequired(c As Control, action As Action(Of Control))
    If c.InvokeRequired Then
        c.Invoke(New Action(Sub() action(c)))
    Else
        action(c)
    End If
End Sub

并把你的东西放进去:

    InvokeIfRequired(Me.Size, 
       Sub()
            For index As Integer = 1 To 50000
                If Screen.PrimaryScreen.Bounds.Width = (Screen.PrimaryScreen.Bounds.Width + 17) Then
                    Exit For
                End If
                Dim screenWidth As Integer = Screen.PrimaryScreen.Bounds.Width
                screenWidth = (screenWidth + 17)
                Dim screenHeight As Integer = Screen.PrimaryScreen.Bounds.Height
                Me.Size = New System.Drawing.Size(screenWidth, screenHeight) 'Here it errors at
                GeckoWebBrowser1.Size = New System.Drawing.Size(screenWidth, screenHeight)
                Me.Location = New Point(0, 0)
            Next
        End Sub)

这样,如果需要,它会被调用。

更新

我只想指出,有些评论非常有帮助。 @djv 描述了一个不错的扩展,并且 @Visual Vincent 指出,你应该尽可能少地调用。