Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
943 views
in Technique[技术] by (71.8m points)

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

The usual VB way to handle a computationally heavy task is to put it in a background worker thread, while the main thread keeps handling the UI.

Say for whatever reason I needed to do this the other way around: the main thread doing the grunt work and the background one updating the UI.

Here's what I have so far. The only problem is, while the UI window (Form1) does get redrawn, you can't interact with it, not even move or resize it (the mouse cursor turns to hourglass and won't click).

Public Class ProgressDisplay

Private trd As Thread

    Public Sub New()
        trd = New Thread(AddressOf threadtask)
        trd.Start()
    End Sub

    Private Sub threadtask()
        Dim f1 As Form1
        f1 = New Form1
        f1.Show()
        Do
            f1.Update()
            Thread.Sleep(100)
        Loop
    End Sub

End Class

Edit: Ideally I need to present an interface like this to the client

Public Class ProgressDisplay
    Public Sub New()
    Public Sub Update(byval progress as int)
End Class

The client will call it like this (actually in unmanaged c++ over COM but you get the picture):

Dim prog = new ProgressDisplay()
DoLotsOfWork(addressof prog.update) ' DoLotsOfWork method takes a callback argument to keep client informed of progress
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...