我有两种形式 它运行正常,但如果我按模式窗体的取消按钮然后显示错误。 任何人都可以帮我解决问题吗? 我的代码如下:
1)
Public Class FRMWait
Public MinValue As Integer = 0
Public MaxValue As Integer = 100
Private Sub FRMWait_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With Me
.ProgressBa1.MinimumValue = .MinValue
.ProgressBa1.MaximumValue = .MaxValue
End With
End Sub
Public Sub UpdateBar(ByVal Progress As Integer)
With Me
.ProgressBarControlProgress.value = Progress
End With
End Sub
Private Sub ButtonCancel_Click(sender As Object, e As EventArgs) Handles ButtonCancel.Click
With Me
.DialogResult = DialogResult.Cancel
End With
End Sub
End Class
2)
Imports System.Threading
Public Class FRMTest
Private WaitForm As New FRMWait
Private _CTS As CancellationTokenSource
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Control.CheckForIllegalCrossThreadCalls = False
End Sub
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
With Me
.WaitForm = New FRMWait
._CTS = New CancellationTokenSource()
Try
Await Task.Run(Sub() RunLongTask())
.WaitForm.ShowDialog()
If .WaitForm.DialogResult = DialogResult.Cancel Then
._CTS.Cancel()
End If
Catch Exp As Exception
MsgBox(Exp.Message)
Finally
If ._CTS IsNot Nothing Then ._CTS = Nothing
End Try
End With
End Sub
Private Async Sub RunLongTask()
With Me
.WaitForm.MinValue = 0
.WaitForm.MaxValue = 100
For i = 0 To 100
If ._CTS.IsCancellationRequested Then
Await Task.Delay(1000)
Exit For
End If
.WaitForm.UpdateBar(i)
Await Task.Delay(100)
Next
.WaitForm.Close()
End With
End Sub
End Class