Visual Basic.NET: how to create a thread to update the UI

你说的曾经没有我的故事 提交于 2019-11-28 10:35:40

To clearly restate the problem - you need to provide a visual component to a client who will use it within their own program. The client's program, outside of your control, ties up its main(ie:UI) thread and you are required to have your visual component continue working while the client's program is frozen.

You CAN do this, but this is probably not the most elegant or recommended solution. You need to create a second application context and a new message loop which can continue running beside the main UI thread. A class something like this would work :

Imports System.Threading

Public Class SecondUIClass

    Private appCtx As ApplicationContext
    Private formStep As Form
    Private trd As Thread
    Private pgBar As ProgressBar
    Delegate Sub dlgStepIt()

    Public Sub New()
        trd = New Thread(AddressOf NewUIThread)
        trd.SetApartmentState(ApartmentState.STA)
        trd.IsBackground = True
        trd.Start()
    End Sub

    Private Sub NewUIThread()
        formStep = New Form()
        pgBar = New ProgressBar()
        formStep.Controls.Add(pgBar)
        appCtx = New ApplicationContext(formStep)
        Application.Run(appCtx)
    End Sub

    Public Sub StepTheBar()
        formStep.Invoke(New dlgStepIt(AddressOf tStepIt))
    End Sub

    Private Sub tStepIt()
        pgBar.PerformStep()
    End Sub

End Class

Essentially what you are doing with the above class is creating a new application context within a new STA thread (giving that thread a message loop). That context contains a main form (giving the thread ownership of it and responsibility for its message processing) which can continue to operate aside from the main UI thread. This is much like having a program within a program - two UI threads, each with their own mutually exclusive set of controls.

Calls which interact with any of the controls owned by the new UI thread (or its form) must be marshalled with Control.Invoke from the primary UI thread (or others) to ensure that your new UI thread is the one doing the interaction. You could also use BeginInvoke here.

This class has NO cleanup code, no checks for safety, etc (be warned) and I'm not even sure it would finish up gracefully - I leave that task to you. This just illustrates a way to get started. In the main form you would do something like :

Public Class Form1

    Private pgClass As New SecondUIClass

    Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
        Dim i As Integer
        For i = 1 To 10
            System.Threading.Thread.Sleep(1000)
            pgClass.StepTheBar()
        Next
    End Sub
End Class

Running the application above would create Form1 as well as a second form created by pgClass. Clicking Button1 on Form1 would lock up Form1 while it went through its loop but the second form would still remain alive and responsive, updating its progress bar each time Form1 called .StepTheBar().

The best solution in this case, really, is to have the 'client' learn how to program properly and avoid being stuck in this conundrum in the first place. In the case where that is completely impossible and you MUST create for them a component whch will remain alive despite their poor code then the above approach is probably your only recourse.

The UI can only be updated via the thread that created it. Any thread can make a request to invoke a method on the UI thread so that it can update the UI, by using the Control.Invoke method, but that will just sit and wait until the UI thread is no longer busy. If the UI thread is busy, the UI cannot be updated by anything or anyone. The UI only gets updated when the main message loop (AKA Application.Run) processes the window messages in the queue and acts upon them. If the UI thread is busy, stuck in a loop or waiting for a response from a server, it can't process those window messages (unless you call DoEvents, which I definitely do not recommend, if at all possible). So, yes, while the UI is busy, it will be locked up. That's the whole reason why everyone suggests doing any hefty business logic in a separate thread. If that wasn't an issue, why would anyone bother making worker threads?

The UI can't be updated from any other thread than the main event dispatching thread. So you are trying to do something that won't work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!