gpt4 book ai didi

vb.net 调用问题

转载 作者:行者123 更新时间:2023-12-02 03:36:14 25 4
gpt4 key购买 nike

我有一个线程运行后台作业,需要偶尔更新 GUI。我的程序经过精心设计,以便当用户单击窗体时,线程和后台操作仍然运行,但控件已被释放(出于内存管理目的)。

我一直在使用 Invoke() 和“If Control.Created = True”来确保线程可以成功更新控件而不会遇到任何异常。但是,重新创建窗体时,所有“Control.Created”值都为 false,并且 Invoke() 失败,并显示“{“在创建窗口句柄之前无法在控件上调用 Invoke 或 BeginInvoke。”}”

我的猜测是,这与以下事实有关:重新创建表单时,它被分配了不同的句柄,并且“Invoke()”正在查看旧句柄。所以我的问题是,如何解决这个问题?

编辑:根据要求,打开表单的代码以及 bg 线程的工作位置

打开 DropLogMDIalt 表单非常简单

    FormCTRL.Show()

当控件被修改以使 NumericUpDown 大于 0(以便有可倒计时的内容)时,后台线程运行

    Private Sub NLauncherTerminateInput_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DLScanInterval.ValueChanged
If DLScanInterval.Created = True Then
DLTimerControlValue = DLScanInterval.Value
If DLTimerControlValue = 0 Then
CancelDropLogTimer()
Else
If DLScanIntervalControl.Active = False Then
BeginDropLogTimer()
End If
End If
End If
End Sub


Public Sub BeginDropLogTimer()
Dim N As New Threading.Thread(AddressOf DropLogTimerIntervalThreadWorker)
N.Start()
DLScanIntervalControl.ThreadID = N.ManagedThreadId
DLScanIntervalControl.Active = True
End Sub

Public Sub CancelDropLogTimer()
DLScanIntervalControl.Active = False
End Sub

Public Sub DropLogTimerIntervalThreadWorker()
DLScanTimerSecondsLeft = DLTimerControlValue * 60
Dim s As Integer = DLTimerControlValue
Do Until 1 = 2
DLScanTimerSecondsLeft = DLTimerControlValue * 60
Do Until DLScanTimerSecondsLeft <= 0
If Not (DLTimerControlValue = 0 Or DLScanIntervalControl.CancelPending = True) Then
Else
Exit Sub
End If

If Not DLTimerControlValue = s Then
DLScanTimerSecondsLeft = DLTimerControlValue * 60
s = DLTimerControlValue
End If

Dim ToInvoke As New MethodInvoker(Sub()
Timer(DLScanTimerSecondsLeft, ":", DLScanIntervalTB)
End Sub)
If (Me.IsHandleCreated) Then
If (InvokeRequired) Then
Invoke(ToInvoke)
Else
ToInvoke()
End If
End If


Threading.Thread.Sleep(1000)
DLScanTimerSecondsLeft -= 1
Loop

CompareScan = True
PerformScan()
Loop
End Sub

该线程只是通过声明一个新的线程来调用。线程,但是,我创建了一个类和一个变量,线程用它来检查它是否仍然应该运行(类似于后台工作人员的方式),这是由“DLScanIntervalControl.CancelPending”说明

稍后关闭该表单

Form.Close()

如果用户单击标签,然后使用与上面所示相同的方法 (FormCTRL.Show()),则可以重新打开它

最佳答案

来自MSDN :

"If the control's handle does not yet exist, InvokeRequired searches up the control's parent chain until it finds a control or form that does have a window handle. If no appropriate handle can be found, the InvokeRequired method returns false."

换句话说,您需要验证句柄是否已创建,然后检查是否需要调用。

If(Me.IsHandleCreated) Then
If(Me.InvokeRequired) Then
'...
Else
'...
End If
End If

关于vb.net 调用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24704512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com