VB.Net从后台线程更新UI

时间:2012-12-27 07:25:14

标签: vb.net multithreading

我正在使用VB.Net开发类似项目的调度程序,应用程序从“Sub Main”开始,使用Application.Run(),所有程序代码都是类中的处理程序,在此创建并启动,

Public Sub Main()
  m_App = New myApp
  m_App.Start()
  Application.Run()
End Sub

在myApp内部,有一个控制任务执行的计时器,它将为每个任务启动一个线程,当任务完成时,如果检测到错误,我们会尝试显示警告窗口。我们测试了两种不同的执行线程和主线程之间的通信方式,以便显示警告窗口(frmAlert):

1)通过在任务对象中添加pulic事件,然后将addhandler添加到主线程中的函数

2)使用委托通知主线程

但是,无法显示警报窗口,并且未报告错误。在使用IDE进行调试后,发现警报窗口已成功显示,但在任务线程完成后将关闭。

这是一个简化的任务类(使用两种通信方法进行测试),

Public Class myProcess

    Public Event NotifyEvent()

    Public Delegate Sub NotifyDelegate()
    Private m_NotifyDelegate As NotifyDelegate

    Public Sub SetNotify(ByVal NotifyDelegate As NotifyDelegate)
        m_NotifyDelegate = NotifyDelegate
    End Sub


    Public Sub Execute()
        System.Threading.Thread.Sleep(2000)
        RaiseEvent NotifyEvent()
        If m_NotifyDelegate IsNot Nothing Then m_NotifyDelegate()
    End Sub

End Class

主要的应用类

Imports System.Threading

Public Class myApp
    Private WithEvents _Timer As New Windows.Forms.Timer

    Private m_Process As New myProcess


    Public Sub Start()
        AddHandler m_Process.NotifyEvent, AddressOf Me.NotifyEvent
        m_Process.SetNotify(AddressOf NotifyDelegate)
        ProcessTasks()
    End Sub

    Private Sub Timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _Timer.Tick
        ProcessTasks()
    End Sub

    Public Sub ProcessTasks()
        _Timer.Enabled = False
        '
        Dim m_Thread = New Thread(AddressOf m_Process.Execute)
        m_Thread.Start()
        '
        _Timer.Interval = 30000
        _Timer.Enabled = True
    End Sub

    Public Sub NotifyEvent()
        frmAlert.Show()
    End Sub

    Public Sub NotifyDelegate()
        frmAlert.Show()
    End Sub

End Class

发现frmAlert是使用NotifyEvent或NotifyDelegate显示的,但是当Execute完成时会立即关闭。

我是否知道如何从执行线程中弹出警报窗口,该窗口可以保留在屏幕上直到用户关闭它?

提前致谢!

1 个答案:

答案 0 :(得分:0)

如果您希望在子线程引发和事件时它执行任何操作,则需要确保主线程不会终止。

Public Sub Start()
    AddHandler m_Process.NotifyEvent, AddressOf Me.NotifyEvent
    m_Process.SetNotify(AddressOf NotifyDelegate)
    ProcessTasks()

    Do While True  'You might want to add a boolean condition here to instruct the main program to terminate when you want it to.
        System.Threading.Thread.Sleep(200)
    Loop
End Sub

这将阻止主线程(程序)结束,因此可用于处理子线程引发的任何事件。注意:您的班级没有终止条件。