在处理表单时中止在表单上运行代码?

时间:2014-01-13 17:32:33

标签: vb.net multithreading winforms

我现在正在维护一个庞大而复杂的客户端应用程序。出于安全考虑,它需要与服务器保持连接。它有一个线程处理它自己和服务器之间的所有套接字通信。

当前编写的方式,如果与服务器存在任何通信问题,通信线程将触发关闭并处置所有打开的表单的事件,并将用户返回到初始连接/登录屏幕。

我遇到的问题是,有时这种通信问题可能发生在函数执行过程中(例如被模态形式阻塞的问题)。当处理模态表单和父表单时,该函数仍然完成运行,经常导致异常和错误。

例如,报表表单有一个功能,可以打开一个对话框,接受输入,然后根据该输入运行报表:

'Inside the class for the ReportForm:

Private Sub RunReport()
    'Run code that requests list of reports from server
    _ReportSelectionForm = New frmReportSelection(reportList)
    _ReportSelectionForm.ShowInTaskbar = False
    Me.AddOwnedForm(_ReportSelectionForm)
    _ReportSelectionForm.ShowDialog(Me)

    'the following code will still execute when ReportForm (Me) is disposed:

    username = _ReportSelectionForm.txtUsername

    If (_ReportSelectionForm.DialogResult = Windows.Forms.DialogResult.Ok) Then
        'Run code
    ElseIf (_ReportSelectionForm.DialogResult = Windows.Forms.DialogResult.Cancel) Then
        'Run different code
    End If  

    'etc
End Sub

因此,如果报告选择表单已打开且通信线程超时与服务器的通信,则会触发通信错误事件,从而关闭并处理ReportForm。反过来,这将关闭_ReportSelectionForm对话框。发生这种情况时,即使已经处理了父表单,也可以在“_ReportSelectionForm.ShowDialog(Me)”之后运行代码。这会在“_ReportSelectionForm.DialogResult”或“_ReportSelectionForm.txtUsername”上抛出异常,因为_ReportSelectionForm是Nothing。

如果这是一个孤立的地方,我可以在继续运行该功能之前通过一些额外的检查来处理这个问题,但它已经完成了这个大型程序。

处理此问题的最佳方法是什么?我可以在我正在关闭的表单上中止代码执行吗?

希望我能充分解释。我的Google-Fu让我失望了。提前谢谢。

1 个答案:

答案 0 :(得分:0)

将您的代码更改为:

Dim result as DialogResult = _ReportSelectionForm.ShowDialog(Me)

If (result = Windows.Forms.DialogResult.Ok) Then
    'Run code
ElseIf (result = Windows.Forms.DialogResult.Cancel) Then
    'Run different code
End If  

这样你就不会引用ReportSelectionForm